arrow_back

API Gateway: Qwik Start

Sprawdź swoją wiedzę i podziel się nią ze społecznością.
done
Zyskaj dostęp do ponad 700 praktycznych modułów oraz odznak umiejętności i szkoleń

API Gateway: Qwik Start

Moduł 1 godz. universal_currency_alt 1 punkt show_chart Wprowadzające
info Ten moduł może zawierać narzędzia AI, które ułatwią Ci naukę.
Sprawdź swoją wiedzę i podziel się nią ze społecznością.
done
Zyskaj dostęp do ponad 700 praktycznych modułów oraz odznak umiejętności i szkoleń

GSP872

Google Cloud self-paced labs logo

Overview

API Gateway enables you to provide secure access to your services through a well-defined REST API that is consistent across all of your services, regardless of service implementation. A consistent API:

  • Makes it easy for app developers to consume your services.
  • Enables you to change the backend service implementation without affecting the public API.
  • Enables you to take advantage of the scaling, monitoring, and security features built into the Google Cloud.

In this lab, you will deploy an API on API Gateway to secure traffic to a backend service.

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left. Navigation menu icon

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Set the region

Set the project region for this lab:

gcloud config set compute/region {{{project_0.default_region | "REGION"}}}

Enable the required APIs

  1. In the Cloud Console, on the Navigation menu (Navigation menu icon) click APIs & Services > Library.

  2. Start typing "api gateway" in the Search bar, then select the API Gateway API tile.

  3. Now click the Enable button on the next screen.

Task 1. Deploying an API backend

API Gateway sits in front of a deployed backend service and handles all incoming requests. In this lab, API Gateway routes incoming calls to a Cloud Function backend named helloGET that contains the function shown below:

/** * HTTP Cloud Function. * This function is exported by index.js, and is executed when * you make an HTTP request to the deployed function's endpoint. * * @param {Object} req Cloud Function request context. * More info: https://expressjs.com/en/api.html#req * @param {Object} res Cloud Function response context. * More info: https://expressjs.com/en/api.html#res */ exports.helloGET = (req, res) => { res.send('Hello World!'); };
  1. In Cloud Console, clone the Cloud Function sample repository:
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
  1. Change to the directory that contains the Cloud Functions sample code:
cd nodejs-docs-samples/functions/helloworld/helloworldGet
  1. To deploy the function with an HTTP trigger, run the following command in the directory containing your function:
gcloud functions deploy helloGET --runtime nodejs20 --trigger-http --allow-unauthenticated --region {{{project_0.default_region | "REGION"}}}
  • If prompted, enter Y to enable the API.
Note: If you receive a request to permit the gcloud command with your credentials click Authorize. It will take a few minutes to deploy the cloud function. Wait for the operation to complete before proceeding. Warning: If you receive an Error as IamPermissionDeniedException rerun the above command.

Click Check my progress to verify the objective. Deploying an API Backend

Task 2. Test the API backend

  1. When the function finishes deploying, take note of the httpsTrigger's url property or find it using the following command:
gcloud functions describe helloGET --region {{{project_0.default_region | "REGION"}}}

The output should look similar to the URL below where PROJECT_ID is a value specific to your project.

  1. Set your PROJECT_ID as a variable:
export PROJECT_ID={{{project_0.project_id}}}
  1. Visit the URL to invoke the Cloud Function. You should see the message Hello World! as the response:
curl -v https://{{{project_0.default_region | "REGION"}}}-{{{project_0.project_id | "PROJECT_ID"}}}.cloudfunctions.net/helloGET

Click Check my progress to verify the objective. Test the API Backend

Create the API definition

API Gateway uses an API definition to route calls to the backend service. You can use an OpenAPI spec that contains specialized annotations to define the desired API Gateway behavior. The OpenAPI spec for this quickstart contains routing instructions to the Cloud Function backend.

  1. From Cloud Shell, navigate back to your home directory:
cd ~
  1. Create a new file named openapi2-functions.yaml:
touch openapi2-functions.yaml
  1. Copy and paste the contents of the OpenAPI spec shown below into the newly created file:
# openapi2-functions.yaml swagger: '2.0' info: title: API_ID description description: Sample API on API Gateway with a Google Cloud Functions backend version: 1.0.0 schemes: - https produces: - application/json paths: /hello: get: summary: Greet a user operationId: hello x-google-backend: address: https://{{{project_0.default_region | "REGION"}}}-{{{project_0.project_id | "PROJECT_ID"}}}.cloudfunctions.net/helloGET responses: '200': description: A successful response schema: type: string
  1. Set the following environment variables:
export API_ID="hello-world-$(cat /dev/urandom | tr -dc 'a-z' | fold -w ${1:-8} | head -n 1)"
  1. Run the following commands to replace the variables set in the last step in the OpenAPI spec file:
sed -i "s/API_ID/${API_ID}/g" openapi2-functions.yaml sed -i "s/PROJECT_ID/$PROJECT_ID/g" openapi2-functions.yaml

Task 3. Creating a gateway

Now you are ready to create and deploy a gateway on API Gateway.

  1. In the top search bar enter API Gateway and select it from the options that appear.

  2. Click Create Gateway. Then, in the APIs section:

  • Ensure the Select an API input is set to Create new API.
  • For Display Name enter Hello World API
  • For API ID, run the following command to once again obtain the API ID and enter it into the API ID field:
export API_ID="hello-world-$(cat /dev/urandom | tr -dc 'a-z' | fold -w ${1:-8} | head -n 1)" echo $API_ID
  1. In the API Config section:
  • Ensure the Select a Config input is set to Create new API config.
  • Do the following to upload the openapi2-functions.yaml file previously created.
  1. In Cloud Shell, run the following command:
cloudshell download $HOME/openapi2-functions.yaml
  1. Click Download.
Note: The file openapi2-functions.yaml is now downloaded to your local machine.
  1. Select Browse and select the file from the browser's download location:
  • Enter Hello World Config in the Display Name field.
  • Ensure the Select a Service Account input is set to Compute Engine default service account.
  1. In the Gateway details Section:
  • Enter Hello Gateway in the Display Name field.
  • Set the Location drop down to .
  1. Click Create Gateway.
Note: It will take several minutes (~10 minutes) for the Create Gateway operation to complete. To check the status of the creation and deployment process, you can click the Notification icon in the main navigation bar to display a status notification, as shown in the image below. Please ensure that the icon status has a green check next to it before proceeding.

Click Check my progress to verify the objective. Creating a Gateway

Testing your API Deployment

Now you can send requests to your API using the URL generated upon deployment of your gateway.

  1. In Cloud Shell, enter the following command to retrieve the GATEWAY_URL of the newly created API hosted by API Gateway:
export GATEWAY_URL=$(gcloud api-gateway gateways describe hello-gateway --location {{{project_0.default_region | "REGION"}}} --format json | jq -r .defaultHostname)
  1. Run the following command to ensure that the GATEWAY_URL environment variable is set:
echo $GATEWAY_URL

If it is not, that means you will need to wait longer for the API Gateway to be deployed.

  1. Run the following curl command and validate that the response returned is Hello World!:
curl -s -w "\n" https://$GATEWAY_URL/hello

Task 4. Securing access by using an API key

To secure access to your API backend, you can generate an API key associated with your project and grant that key access to call your API. To create an API Key you must do the following:

  1. In the Cloud Console, navigate to APIs & Services > Credentials.
  2. Select Create credentials, then select API Key from the dropdown menu. The API key created dialog box displays your newly created key.

Create credential drop-down menu.

Click Check my progress to verify the objective. Securing Access by Using an API Key

  1. Copy the API Key from the dialog, then click on close.

  2. Store the API Key value in Cloud Shell by running the following command:

export API_KEY=REPLACE_WITH_COPIED_API_KEY

Now, enable the API Key support for your service.

  1. In Cloud Shell, obtain the name of the Managed Service you just created using the following command:
MANAGED_SERVICE=$(gcloud api-gateway apis list --format json | jq -r .[0].managedService | cut -d'/' -f6) echo $MANAGED_SERVICE
  1. Then, using the Managed Service name of the API you just created, run this command to enable API key support for the service:
gcloud services enable $MANAGED_SERVICE

Modify the OpenAPI Spec to leverage API Key Security

In this section, modify the API config of the deployed API to enforce an API key validation security policy on all traffic.

  1. Add the security type and securityDefinitions sections to a new file called openapi2-functions2.yaml file as shown below:
touch openapi2-functions2.yaml
  1. Copy and paste the contents of the OpenAPI spec shown below into the newly created file:
# openapi2-functions.yaml swagger: '2.0' info: title: API_ID description description: Sample API on API Gateway with a Google Cloud Functions backend version: 1.0.0 schemes: - https produces: - application/json paths: /hello: get: summary: Greet a user operationId: hello x-google-backend: address: https://{{{project_0.default_region | "REGION"}}}-{{{project_0.project_id | "PROJECT_ID"}}}.cloudfunctions.net/helloGET security: - api_key: [] responses: '200': description: A successful response schema: type: string securityDefinitions: api_key: type: "apiKey" name: "key" in: "query"
  1. Run the following commands to replace the variables set in the last step in the OpenAPI spec file:
sed -i "s/API_ID/${API_ID}/g" openapi2-functions2.yaml sed -i "s/PROJECT_ID/$PROJECT_ID/g" openapi2-functions2.yaml
  1. Download the updated API spec file, you will use it to update the Gateway config in the next step:
cloudshell download $HOME/openapi2-functions2.yaml
  1. Click Download.

Task 5. Create and deploy a new API config to your existing gateway

  1. Open the API Gateway page in Cloud Console. (Click Navigation Menu > API Gateway.)
  2. Select your API from the list to view details.
  3. Select the Gateways tab.
  4. Select Hello Gateway from the list of available Gateways.
  5. Click on Edit at the top of the Gateway page.
  6. Under API Config change the drop down to Create new API config.
  7. Click Browse in the Upload an API Spec input box and select the openapi2-functions2.yaml file.
  8. Enter Hello Config for Display Name.
  9. Select Qwiklabs User Service Account for Select a Service Account.
  10. Click Update.
Note: It may take a few minutes for the Update Gateway operation to complete. To check the status of the creation and deployment process, you can click the Notification icon in the main navigation bar to display a status notification, as shown in the image below. Please ensure that the icon status has a green check next to it before proceeding.

Click Check my progress to verify the objective. Create and deploy a new API config to your existing gateway

Task 6. Testing calls using your API key

  1. To test using your API key run the following command:
export GATEWAY_URL=$(gcloud api-gateway gateways describe hello-gateway --location {{{project_0.default_region | "REGION"}}} --format json | jq -r .defaultHostname) curl -sL $GATEWAY_URL/hello

You should see a response similar to the following error as an API key was not supplied with the curl call: UNAUTHENTICATED:Method doesn't allow unregistered callers (callers without established identity). Please use API Key or other form of API consumer identity to call this API.

  1. Run the following curl command with the key query parameter and use the API key previously created to call the API:
curl -sL -w "\n" $GATEWAY_URL/hello?key=$API_KEY

If you do not have the API_KEY environment variable set you can get your API key from the left menu by navigating APIs & Services > Credentials. The key will be available under the API Keys section.

The response returned from the API should now be Hello World!.

Note: You may need to run this command more than once to obtain the desired result.

Click Check my progress to verify the objective. Testing Calls Using Your API Key

Congratulations!

You have successfully protected an API backend with API Gateway. Now you can start onboarding new API clients by generating additional API keys.

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated October 09, 2024

Lab Last Tested October 09, 2024

Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

Ta treść jest obecnie niedostępna

Kiedy dostępność się zmieni, wyślemy Ci e-maila z powiadomieniem

Świetnie

Kiedy dostępność się zmieni, skontaktujemy się z Tobą e-mailem