Secure traffic to a service with the Google Cloud console
This page shows you how to deploy an API on API Gateway to secure traffic to a backend service.
Follow the steps below to deploy a new API to access a backend service on Cloud Run functions using the Google Cloud console. This quickstart also describes how to use an API key to protect your backend from unauthorized access.
Before you begin
In the Google Cloud console, go to the API Gateway page and select or create a Google Cloud project.
API Gateway requires that you enable the following Google services:
Name Title apigateway.googleapis.com
API Gateway API servicemanagement.googleapis.com
Service Management API servicecontrol.googleapis.com
Service Control API If you have not previously enabled these services for the project you select, you will be prompted to do so.
Confirm that billing is enabled for your project.
Deploying an API backend
API Gateway sits in front of a deployed backend service and handles all incoming requests. In this quickstart, API Gateway routes incoming calls to a Cloud Run 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!'); };
Follow the steps in Quickstart: Using the Google Cloud CLI to download the sample Cloud Run functions code and deploy the Cloud Run function backend service.
Creating an 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 Run function backend:
# openapi2-functions.yaml swagger: '2.0' info: title: API_ID optional-string 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://us-central1-PROJECT_ID.cloudfunctions.net/helloGET responses: '200': description: A successful response schema: type: string
To use the OpenAPI spec shown above to define your API:
From the command line, create a new file named
openapi2-functions.yaml
.Copy and paste the contents of the OpenAPI spec shown above into the newly created file.
Edit the file as follows:
- In the
title
field, replace API_ID with the name of your API (which will be created in the next step) and replace optional-string with a brief description of your choosing. The value of this field is used when minting API keys that grant access to this API. See API ID requirements for API ID naming guidelines. - In the
address
field, replace PROJECT_ID with the name of your Google Cloud project.
- In the
Creating a gateway
Now you are ready to create and deploy a gateway on API Gateway.
Open the API Gateway page in the Google Cloud console.
Click Create Gateway.
In the API section:
- You can choose to create a new API or select an existing API from the Select an API dropdown. For this tutorial, select Create a new API.
- Enter the Display Name for your API.
- Enter the API ID for your API.
- (Optional) Add labels to your API using a key/value format. To add more than one label, click Add Label and enter additional values.
In the API Config section:
- You can choose to create a new API config or select an existing API config from the Select a Config dropdown. For this tutorial, select Create a new API config.
- Use the file browser to upload the
openapi2-functions.yaml
used to define your API. - Enter a display name for your API config.
Select a service account from the dropdown list. The service account you select will be used as identity for API Gateway.
(Optional) Add labels to your API config using a key/value format. To add more than one label, click Add Label and enter additional values.
In the Gateway details section:
- Enter the display name of the gateway. The URL to the gateway is automatically generated.
- Select the location of the gateway from the dropdown menu.
- (Optional) Add labels to your gateway using a key/value format. To add more than one label, click Add Label and enter additional values.
Click Create Gateway.
This deploys the API config on a newly created gateway. Deploying an API config on a gateway defines an external URL that API clients can use to access your API.
It may take several minutes for the 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:
On successful completion, you can view details about the gateway on the Gateways landing page.
Make a note of the gateway URL. This is used to test your deployment in the next step.
Testing your API deployment
Now you can send requests to your API using the URL generated upon deployment of your gateway.
In your browser, enter the following URL, where:
- GATEWAY_URL specifies your deployed gateway URL.
hello
is the path specified in your API config.
https://GATEWAY_URL/hello
For example:
https://my-gateway-a12bcd345e67f89g0h.uc.gateway.dev/hello
The message Hello World!
should display in your browser.
You have successfully created and deployed an API Gateway!
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. See Restricting API access with API keys for more information.
If you do not already have an API key associated with the Google Cloud project you are using in this quickstart, you can add one by following the steps at Creating an API Key.
To secure access to your gateway using an API key:
- Enable API key support for your service:
- In the Google Cloud console, go to APIs & Services > Library.
- In the search bar, enter the Managed Service name of the API you just created. You can find this value in the Managed Service column for your API on the APIs landing page.
For example:
my-api-123abc456def1.apigateway.my-project.cloud.goog
- On the landing page for your service, click Enable.
- Modify the OpenAPI spec used to create your API config to include instructions to enforce an API key validation security policy on all traffic. Add the
security
type andsecurityDefinitions
as shown below:# openapi2-functions.yaml swagger: '2.0' info: title: API_ID optional-string 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://us-central1.PROJECT_ID.cloudfunctions.net/helloGET security: - api_key: [] responses: '200': description: A successful response schema: type: string securityDefinitions: # This section configures basic authentication with an API key. api_key: type: "apiKey" name: "key" in: "query"
ThesecurityDefinition
configures your API to require an API key passed as a query parameter namedkey
when requesting access to all paths defined in the spec. - Create and deploy a new API config to your existing gateway:
- Go to the Gateways landing page.
- Select your gateway from the list to view details.
- Click Edit to open the gateway configuration pane.
- In the API config section:
- Select Create a new API config from the available dropdown.
- Upload your modified OpenAPI spec using the file browser.
- Enter the display name for your new API config.
- Select a service account from the dropdown list. The service account you select will be used as the identity for API Gateway.
- (Optional) Add labels to your API config using a key/value format. To add more than one label, click Add Label and enter additional values.
- Click Update.
Testing your API key
Once you have created and deployed the modified API, try making a request to it.
In your browser, enter the following URL, where:
- GATEWAY_URL specifies your deployed gateway URL.
hello
is the path specified in your API config.
https://GATEWAY_URL/hello
For example:
https://my-gateway-a12bcd345e67f89g0h.uc.gateway.dev/hello
This should result in the following error:
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.
Now, in your browser, enter the following URL, where:
- GATEWAY_URL specifies your deployed gateway URL.
hello
is the path specified in your API config.- API_KEY specifies the API key you created in Securing access by using an API key.
https://GATEWAY_URL/hello?key=API_KEY
Now you should see Hello World!
in your browser.
Congratulations! You have successfully protected your API backend with an API Gateway. Now you can start onboarding new API clients by generating additional API keys.
Tracking API activity
View the activity graphs for your API on the API Gateway page in the Google Cloud console. Click on your API to view its activity graphs on the Overview page. It may take a few moments for the requests to be reflected in the graphs.
Look at the request logs for your API on the Logs Explorer page. A link to the Logs Explorer page can be found on the API Gateway page in the Google Cloud console.
Once on the API Gateway page:- Select the API to view.
- Click the Details tab.
- Click the link under Logs.
Clean up
To avoid incurring charges to your Google Cloud account for the resources used in this quickstart, you can:
Alternatively, you can also delete the Google Cloud project used for this tutorial.
What's next
- Learn more About API Gateway
- Walk through Configuring your development environment