Quickstart: 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 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

  1. In the Google Cloud console, go to the API Gateway page.

    Go to API Gateway

  2. 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 are prompted to do so.

  3. Confirm that billing is enabled for your project.

    Learn how to enable billing

Deploy 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 as follows:

/**
 * 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.

Create an API config

API Gateway uses an API config to route calls to the backend service. You can use an OpenAPI specification that contains specialized extensions to define the chosen API Gateway behavior. For more details on supported OpenAPI extensions, see the following:

The OpenAPI specification for this quickstart contains routing instructions to the Cloud Run function backend:

OpenAPI 2.0

# openapi-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://GATEWAY_LOCATION -PROJECT_ID.cloudfunctions.net/helloGET
      responses:
        '200':
          description: A successful response
          schema:
            type: string

OpenAPI 3.x

# openapi-functions.yaml
openapi: 3.0.4
info:
  title: API_ID optional-string
  description: Sample API on API Gateway with a Google Cloud Functions backend
  version: 1.0.0
# Define reusable components in x-google-api-management
x-google-api-management:
  backend:
    functions_backend:
      address: https://GATEWAY_LOCATION-PROJECT_ID.cloudfunctions.net/helloGET
      pathTranslation: APPEND_PATH_TO_ADDRESS
      protocol: "http/1.1"
# Apply the backend configuration by referencing it by name. Set at the root so this applies to all operations unless overridden.
x-google-backend: functions_backend
paths:
  /hello:
    get:
      summary: Greet a user
      operationId: hello
      responses:
        '200':
          description: A successful response
          content:
            application/json:
              schema:
                type: string

Use this OpenAPI specification to define your API:

  1. From the command line, create a new file named openapi-functions.yaml.

  2. Copy and paste the contents of the OpenAPI specification shown in the previous example into the newly created file.

  3. Edit the file as follows:

    1. In the title field, replace API_ID with the name of your API (which you create 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.
    2. In the address field, replace PROJECT_ID with the name of your Google Cloud project and replace GATEWAY_LOCATION with the Google Cloud where your gateway is deployed.

Create a gateway

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

  1. Open the API Gateway page in the Google Cloud console.

    Go to API Gateway

  2. Click Create Gateway.

  3. In the API section:

    1. Choose to create a new API or select an existing API from the Select an API drop-down. For this tutorial, select Create a new API.
    2. Enter the Display Name for your API.
    3. Enter the API ID for your API.
    4. (Optional) Add labels to your API using a key:value format. To add more than one label, click Add Label and enter additional values.
  4. In the API Config section:

    1. Choose to create a new API config or select an existing API config from the Select a Config drop-down. For this tutorial, select Create a new API config.
    2. Use the file browser to upload the openapi-functions.yaml used to define your API.
    3. Enter a display name for your API config.
    4. Select a service account from the drop-down list. The service account you select is used as identity for API Gateway.

    5. (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.

  5. In the Gateway details section:

    1. Enter the display name of the gateway. The URL to the gateway automatically generates.
    2. Select the location of the gateway from the drop-down menu.
    3. (Optional) Add labels to your gateway using a key:value format. To add more than one label, click Add Label and enter additional values.
  6. 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.

The operation may take several minutes to complete. To check the status of the creation and deployment process, click the Notification icon in the main navigation bar to display a status notification, as shown in the following image:

Notification panel for status notifications

On successful completion, you can view details about the gateway on the Gateways landing page.

Go to API Gateway

Make a note of the gateway URL. You use this to test your deployment in the next step.

Test 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!

Secure access with an API key

To secure access to your API backend, 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 don't already have an API key associated with the Google Cloud project you are using in this quickstart, add one by following the steps at Creating an API Key.

To secure access to your gateway using an API key:

  1. Enable API key support for your service:
    1. In the Google Cloud console, go to APIs & Services > Library.
    2. 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
    3. On the landing page for your service, click Enable.
  2. Modify the OpenAPI specification used to create your API config to include instructions to enforce an API key validation security policy on all traffic. Add the security type and securitySchemes as shown:

    OpenAPI 2.0

      # 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://GATEWAY_LOCATION-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"

    The securityDefinition configures your API to require an API key passed as a query parameter named key when requesting access to all paths defined in the specification.

    OpenAPI 3.x

    # openapi-functions.yaml
    openapi: 3.0.4
    info:
      title: API_ID optional-string
      description: Sample API on API Gateway with a Google Cloud Functions backend
      version: 1.0.0
    # Define reusable components in x-google-api-management
    x-google-api-management:
      backend:
        functions_backend:
          address: https://GATEWAY_LOCATION-PROJECT_ID.cloudfunctions.net/helloGET
          pathTranslation: APPEND_PATH_TO_ADDRESS
          protocol: "http/1.1"
    # Apply the backend configuration by referencing it by name. Set at the root so this applies to all operations unless overridden.
    x-google-backend: functions_backend
    components:
    # This section configures basic authentication with an API key.
      securitySchemes:
        google_api_key:
          type: apiKey
          name: x-api-key
          in: header
    security:
      - google_api_key: []
    paths:
      /hello:
        get:
          summary: Greet a user
          operationId: hello
          responses:
            '200':
              description: A successful response
              content:
                application/json:
                  schema:
                    type: string

    The securitySchemes configures your API to require an API key passed as a query parameter named key when requesting access to all paths defined in the specification.

  3. Create and deploy a new API config to your existing gateway:
    1. Go to the Gateways landing page.

      Go to API Gateway

    2. Select your gateway from the list to view details.
    3. Click Edit to open the gateway configuration pane.
    4. In the API config section:
      1. Select Create a new API config from the available drop-down.
      2. Upload your modified OpenAPI specification using the file browser.
      3. Enter the display name for your new API config.
      4. Select a service account from the drop-down list. The service account you select is used as the identity for API Gateway.
      5. (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.
    5. Click Update.

Test 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

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.

Track API activity

  1. View the activity graphs for your API on the API Gateway page in the Google Cloud console. Click your API to view its activity graphs on the Overview page. It may take a few moments for the requests to reflect in the graphs.

  2. 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.

    Go to API Gateway

    Once on the API Gateway page:

    1. Select the API to view.
    2. Click the Details tab.
    3. 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