Getting Started with Endpoints for Cloud Functions

This page shows you how to set up Cloud Endpoints for Cloud Functions. Endpoints uses the Extensible Service Proxy (ESP) as an API gateway. To provide API management for Cloud Functions, you deploy the prebuilt ESP container to Cloud Run. You then secure your functions by using Cloud Functions IAM so that ESP can invoke them. With this set up, ESP intercepts all requests to your functions and performs any necessary checks (such as authentication) before invoking the function. When the function responds, ESP gathers and reports telemetry. You can view metrics for your function on the Endpoints > Services page in the Google Cloud Platform Console.

For an overview of Cloud Endpoints, see About Endpoints and Endpoints architecture.

Task List

Use the following task list as you work through the tutorial. All tasks are required for Endpoints to manage your functions.

  1. Create a Google Cloud Platform (GCP) project, and if you haven't deployed your own Cloud Functions, deploy a sample function. See Before you begin.
  2. Deploy the ESP container to Cloud Run. See Deploying ESP.
  3. Create an OpenAPI document that describes your API, and configure the routes to your Cloud Functions. See Configuring Endpoints.
  4. Deploy the OpenAPI document to create a managed service. See Deploying the Endpoints configuration.
  5. Configure ESP so it can find the configuration for your service, and grant ESP the Cloud Identity and Access Management (Cloud IAM) permission to invoke your functions. See Configuring ESP.
  6. Invoke a function. See Sending a request to the API.
  7. Track activity to your functions. See Tracking API activity.
  8. Avoid incurring charges to your GCP account. See Clean up.

Before you begin

Because Endpoints for Cloud Functions is in beta, we recommend that you:

  • Create a new GCP project to use when you deploy the ESP container to Cloud Run.

  • Either create a new or select an existing project for your Cloud Functions.

To get set up:

  1. In the GCP Console, go to the Manage resources page and create a project.

    Go to the Manage resources page

  2. Make sure that billing is enabled for your project.

    Learn how to enable billing

  3. Make a note of the project ID because it is needed later. On the rest of this page, this project ID is referred to as ESP_PROJECT_ID.

  4. Make a note of the project number because it is needed later. On the rest of this page, this project number is referred to as ESP_PROJECT_NUMBER.

  5. Download and install the Cloud SDK.

    Download the Cloud SDK

  6. If you haven't deployed your own Cloud Functions, follow the steps in Quickstart: Using the gcloud command-line tool to select or create a GCP project and deploy a sample function. Make a note of the region and project ID where your functions are deployed. On the rest of this page, this project ID is referred to as FUNCTIONS_PROJECT_ID.

Deploying ESP

To deploy the ESP container to Cloud Run:

  1. Make sure that Cloud SDK is authorized to access your data and services.
    1. Log in.
      gcloud auth login
    2. On the new browser tab that opens, choose an account that has the Editor or Owner role in the GCP project that you created for deploying ESP to Cloud Run.
  2. Set the region. Currently, only us-central1 is supported for Cloud Run.
    gcloud config set run/region us-central1
  3. Deploy ESP to Cloud Run. Replace CLOUD_RUN_SERVICE_NAME with the name that you want to use for the service.
    gcloud beta run deploy CLOUD_RUN_SERVICE_NAME \
        --image="gcr.io/endpoints-release/endpoints-runtime-serverless:1" \
        --allow-unauthenticated \
        --project=ESP_PROJECT_ID
    

    On successful completion, the command displays a message similar to the following:

    Service [gateway] revision [gateway-00001] has been deployed and is serving
    traffic at https://gateway-12345-uc.a.run.app

    In the preceding example, gateway is the name of the Cloud Run service.

  4. Make a note of the hostname in the URL. You specify the hostname in the host field of your OpenAPI document.
  5. Your Cloud Run service is public on the internet. If you want to add authentication capabilities, we recommend that you use one of the authentication methods supported by Endpoints.

Configuring Endpoints

You must have an OpenAPI document based on OpenAPI Specification v2.0 that describes the surface of your functions and any authentication requirements. You also need to add a Google-specific field that contains the URL for each function so that ESP has the information it needs to invoke a function. If you are new to OpenAPI, see OpenAPI overview for more information

  1. Create a text file called openapi-functions.yaml. (For convenience, this page refers to the OpenAPI document by that file name, but you can name it something else if you prefer.)
  2. Each of your functions must be listed in the paths section of the openapi-functions.yaml file. For example:
    swagger: '2.0'
    info:
      title: Cloud Endpoints + GCF
      description: Sample API on Cloud Endpoints with a Google Cloud Functions backend
      version: 1.0.0
    host: HOST
    schemes:
      - https
    produces:
      - application/json
    paths:
      /hello:
        get:
          summary: Greet a user
          operationId: hello
          x-google-backend:
            address: https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/helloGET
          responses:
            '200':
              description: A successful response
              schema:
                type: string
    
    Please note that indentation is important for yaml format. For example "host" field must be at same level as "info".
  3. In the address field in the x-google-backend section, replace REGION with the GCP region where your function is located, and FUNCTIONS_PROJECT_ID with your GCP project ID. (You can run gcloud functions describe to get the region.)
  4. In the host field, add the hostname of the serving URL that Cloud Run created for ESP. Don't include the protocol identifier, https://. For example:
    swagger: '2.0'
      info:
        title: Cloud Endpoints + GCF
        description: Sample API on Cloud Endpoints with a Google Cloud Functions backend
        version: 1.0.0
      host: gateway-12345-uc.a.run.app
    

    Endpoints uses the name you configure in the host field as the name of your service.

  5. Save your OpenAPI document.

For information about the fields in the OpenAPI document that Endpoints requires, see Configuring Endpoints.

Deploying the Endpoints configuration

To deploy the Endpoints configuration, you use the gcloud endpoints services deploy command. This command uses Service Management to create a managed service.

To deploy the Endpoints configuration:

  1. Make sure you are in the directory that contains your OpenAPI document.

  2. Upload the configuration and create a managed service.

    gcloud endpoints services deploy openapi-functions.yaml \
      --project ESP_PROJECT_ID
    

    This creates a new Endpoints service with the name that you specified in the host field of the openapi-functions.yaml file. The service is configured according to your OpenAPI document.

As it is creating and configuring the service, Service Management outputs information to the terminal. When the deployment completes, a message similar to the following is displayed:

Service Configuration [2019-02-01-r0] uploaded for service [gateway-12345-uc.a.run.app]

In the previous example, 2019-02-01-r0 is the service configuration ID and gateway-12345-uc.a.run.app is the Endpoints service name. The service configuration ID consists of a date stamp followed by a revision number. If you deploy openapi-functions.yaml again on the same day, the revision number is incremented in the service configuration ID. You can view the service configuration and the deployment history on the Endpoints > Services page in the GCP Console.

If you get an error message, see Troubleshooting Endpoints configuration deployment.

Checking required services

At a minimum, Endpoints and ESP require the following services:
Name Title
servicemanagement.googleapis.com Service Management API
servicecontrol.googleapis.com Service Control API
endpoints.googleapis.com Google Cloud Endpoints

In most cases, the gcloud endpoints services deploy command enables these required services. However, the gcloud command completes successfully but doesn't enable the required services in the following circumstances:

  • If you used a third-party application such as Terraform, and you don't include these services.

  • You deployed the Endpoints configuration to an existing GCP project in which these services were explicitly disabled.

To confirm that the required services are enabled:

gcloud services list

If you don't see the required services listed, enable them:

gcloud services enable SERVICE_NAME

Replace SERVICE_NAME with the name of the service to enable.

For more information about the gcloud commands, see gcloud services.

Configuring ESP

Configure ESP so it can find the configuration for your Endpoints service. Then grant ESP the Cloud IAM permission to invoke your functions.

To configure ESP:

  1. Set the Endpoints service name so that ESP can locate and load your Endpoints configuration. In the following command:

    • Replace YOUR_SERVICE_NAME with the name of your Endpoints service. This is the name that you specified in the host field of your OpenAPI document.
    • Replace CLOUD_RUN_SERVICE_NAME with the name of your Cloud Run service.
    gcloud beta run services update CLOUD_RUN_SERVICE_NAME \
       --set-env-vars ENDPOINTS_SERVICE_NAME=YOUR_SERVICE_NAME \
       --project ESP_PROJECT_ID
    
  2. If you want to configure Endpoints to use additional ESP startup options, such as enabling CORS, you can pass the arguments in the ESP_ARGS environment variable:

    gcloud beta run services update CLOUD_RUN_SERVICE_NAME \
       --set-env-vars="^|^ENDPOINTS_SERVICE_NAME=YOUR_SERVICE_NAME|ESP_ARGS=--rollout_strategy=managed,--cors_preset=basic" \
       --project ESP_PROJECT_ID
    

    You must include the ENDPOINTS_SERVICE_NAME as well as a --rollout_strategy.

  3. Grant ESP permission to invoke your functions. Run the following command for each function. In the following command:

    • Replace FUNCTION_NAME with the name of your function.
    • Replace ESP_PROJECT_NUMBER with the project number of the project that you created for ESP. One way to find this is to go to the IAM console and find the Default compute service account, which is the service account used in the member flag.
    gcloud beta functions add-iam-policy-binding FUNCTION_NAME \
        --member "serviceAccount:ESP_PROJECT_NUMBER-compute@developer.gserviceaccount.com" \
        --role "roles/cloudfunctions.invoker" \
        --project FUNCTIONS_PROJECT_ID
    

For more information, see Managing Access via Cloud IAM.

Sending requests to the API

This section shows how to send requests to your API.

  1. Create an environment variable for your Endpoints service name. This is the name that you specified in the host field of your OpenAPI document. For example:
    • Linux or macOS:

      export ENDPOINTS_HOST=gateway-12345-uc.a.run.app

    • Windows PowerShell:

      $Env: ENDPOINTS_HOST="gateway-12345-uc.a.run.app"

Linux or Mac OS

Use curl to send an HTTP request by using the ENDPOINTS_HOST environment variable you set in the previous step.

curl --request GET \
   --header "content-type:application/json" \
   "https://${ENDPOINTS_HOST}/hello"

PowerShell

Use Invoke-WebRequest to send an HTTP request by using the ENDPOINTS_HOST environment variable you set in the previous step.

(Invoke-WebRequest -Method GET `
    -Headers @{"content-type"="application/json"} `
    -URI "https://$Env:ENDPOINTS_HOST/hello").Content

In the previous example, the first two lines end in a backtick. When you paste the example into PowerShell, make sure there isn't a space following the backticks. For information about the options used in the example request, see Invoke-WebRequest in the Microsoft documentation.

Third-party app

You can use a third-party application such as the Chrome browser extension Postman request.

  • Select GET as the HTTP verb.
  • For the header, select the key content-type and the value application/json.
  • Use the actual URL instead of the environment variable, for example:

    https://gateway-12345-uc.a.run.app/hello
    

If you didn't get a successful response, see Troubleshooting Response Errors.

You just deployed and tested an API in Endpoints!

Tracking API activity

  1. View the activity graphs for your API on the Endpoints > Service page in the GCP Console.

    View Endpoints activity graphs

    It may take a few moments for the request to be reflected in the graphs.

  2. Look at the request logs for your API on the Logs Viewer page.

    View Endpoints request logs

Creating a developer portal for the API

You can use Cloud Endpoints Portal to create a developer portal, a website that you can use to interact with the sample API. To learn more, see Cloud Endpoints Portal Overview.

Clean up

To avoid incurring charges to your GCP account for the resources used in this quickstart:

See Deleting an API and API instances for information on stopping the services used by this tutorial.

What's next

Оцените, насколько информация на этой странице была вам полезна:

Оставить отзыв о...

Текущей странице
Cloud Endpoints with OpenAPI
Нужна помощь? Обратитесь в службу поддержки.