Set up Cloud Endpoints OpenAPI for Cloud Run functions with ESPv2
This page shows you how to set up Cloud Endpoints on Cloud Run functions. Endpoints uses the Extensible Service Proxy V2 (ESPv2) as an API gateway. To provide API management for Cloud Run functions, you deploy the prebuilt ESPv2 container to Cloud Run. You then secure your functions by using Cloud Run functions IAM so that ESPv2 can invoke them.
With this set up, ESPv2 intercepts all requests to your functions and performs any necessary checks (such as authentication) before invoking the function. When the function responds, ESPv2 gathers and reports telemetry, as shown in the figure below. You can view metrics for your function on the Endpoints > Services page in the Google Cloud console.
For an overview of Cloud Endpoints, see About Endpoints and Endpoints architecture.
Migrating to ESPv2
Previous releases of Cloud Endpoints supported the use of the Extensible Service Proxy (ESP) with Cloud Functions. If you have existing APIs that you want to migrate to ESPv2, see Migrate to Extensible Service Proxy V2 for more.
Task List
Use the following task list as you work through the tutorial. All tasks are required to complete this tutorial.
- Create a Google Cloud project, and if you haven't deployed your own Cloud Run functions, deploy a sample backend function. See Before you begin.
- Reserve a Cloud Run hostname for the ESPv2 service. See Reserving a Cloud Run hostname.
- Create an OpenAPI document that describes your API, and configure the routes to your Cloud Run functions. See Configuring Endpoints.
- Deploy the OpenAPI document to create a managed service. See Deploying the Endpoints configuration.
- Build a new ESPv2 Docker image with your Endpoints service configuration. See Building a new ESPv2 image.
- Deploy the ESPv2 container onto Cloud Run. Then grant ESPv2 the Identity and Access Management (IAM) permission to invoke your service. See Deploying the ESPv2 container.
- Invoke a function. See Sending a request to the API.
- Track activity to your functions. See Tracking API activity.
- Avoid incurring charges to your Google Cloud account. See Clean up.
Costs
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage,
use the pricing calculator.
When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, see Clean up.
Before you begin
Before using Endpoints for Cloud Run functions, we recommend that you:
Create a new Google Cloud project to use when you deploy the ESPv2 container to Cloud Run.
Either create a new or select an existing project for your Cloud Run functions.
To get set up:
In the Google Cloud console, go to the Manage resources page and create a project.
Make sure that billing is enabled for your project.
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.
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.
Download and install the Google Cloud CLI.
If you haven't deployed your own backend Cloud Run functions, follow the steps in Quickstart: Using the Google Cloud CLI to select or create a Google Cloud 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.
Reserving a Cloud Run hostname
You must reserve a Cloud Run hostname for the ESPv2 service in order to configure the OpenAPI document or gRPC service configuration. To reserve a hostname, you will deploy a sample container to Cloud Run. Later, you will deploy the ESPv2 container onto the same Cloud Run service.
-
Make sure that gcloud CLI is authorized to access your data and
services.
- Log in.
gcloud auth login
- On the new browser tab that opens, choose an account that has the Editor or Owner role in the Google Cloud project that you created for deploying ESPv2 to Cloud Run.
- Log in.
-
Set the region.
gcloud config set run/region us-central1
-
Deploy the sample image
gcr.io/cloudrun/hello
to Cloud Run. Replace CLOUD_RUN_SERVICE_NAME with the name that you want to use for the service.gcloud run deploy CLOUD_RUN_SERVICE_NAME \ --image="gcr.io/cloudrun/hello" \ --allow-unauthenticated \ --platform managed \ --project=ESP_PROJECT_ID
On successful completion, the command displays a message similar to the following:
Service [CLOUD_RUN_SERVICE_NAME] revision [CLOUD_RUN_SERVICE_NAME-REVISION_NUM] has been deployed and is serving traffic at CLOUD_RUN_SERVICE_URL
For example, if you set CLOUD_RUN_SERVICE_NAME to
gateway
:Service [gateway] revision [gateway-00001] has been deployed and is serving traffic at https://gateway-12345-uc.a.run.app
In this example,
https://gateway-12345-uc.a.run.app
is the CLOUD_RUN_SERVICE_URL andgateway-12345-uc.a.run.app
is the CLOUD_RUN_HOSTNAME. - Make a note of CLOUD_RUN_SERVICE_NAME and CLOUD_RUN_HOSTNAME.
You later deploy ESPv2 onto the CLOUD_RUN_SERVICE_NAME Cloud Run service.
You specify CLOUD_RUN_HOSTNAME in the
host
field of your OpenAPI document.
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 ESPv2 has the information it needs to invoke a function. If you are new to OpenAPI, see OpenAPI overview for more information
-
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.) -
Each of your functions must be listed in the
paths
section of theopenapi-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/FUNCTIONS_NAME protocol: h2 responses: '200': description: A successful response schema: type: string
Indentation is important for yaml format. For example thehost
field must be at the same level asinfo
. -
In the
address
field in thex-google-backend
section, replace REGION with the Google Cloud region where your function is located, FUNCTIONS_PROJECT_ID with your Google Cloud project ID and FUNCTIONS_NAME with your function name. For example:x-google-backend: address: https://us-central1-myproject.cloudfunctions.net/helloGET
If you want to secure your Cloud Run function by only allowing ESPv2 to invoke it, make sure theaddress
field includes the function name if thejwt_audience
is not specified. For example:x-google-backend: address: https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/FUNCTIONS_NAME path_translation: CONSTANT_ADDRESS
If thejwt_audience
is specified, its value should include the function name too. For example:x-google-backend: address: https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net jwt_audience: https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/FUNCTIONS_NAME path_translation: APPEND_PATH_TO_ADDRESS
ESPv2 generates an ID token when calling the Cloud Run function for authentication. The ID token should have an properaudience
that specifies the function host and the function name. ESPv2 sets theaudience
for the ID token using the value in thejwt_audience
field if it is specified, otherwise, it uses theaddress
field. In the
host
field, specify CLOUD_RUN_HOSTNAME, the hostname portion of the URL that was reserved above in Reserving a Cloud Run hostname. 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
Note the value of the
title
property in theopenapi-functions.yaml
file:title: Cloud Endpoints + GCF
The value of the
title
property becomes the name of the Endpoints service after you deploy the configuration.- 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:
- Make sure you are in the directory that contains your OpenAPI document.
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 theopenapi-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 [CONFIG_ID] uploaded for service [CLOUD_RUN_HOSTNAME]
CONFIG_ID is the unique Endpoints service configuration ID created by the deployment. For example:
Service Configuration [2019-02-01r0] uploaded for service [gateway-12345-uc.a.run.app]
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 Google Cloud console.If you get an error message, see Troubleshooting Endpoints configuration deployment.
Checking required services
At a minimum, Endpoints and ESP require the following Google services to be enabled: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 Google Cloud project in which these services were explicitly disabled.
Use the following command to confirm that the required services are enabled:
gcloud services list
If you do not see the required services listed, enable them:
gcloud services enable servicemanagement.googleapis.comgcloud services enable servicecontrol.googleapis.com
gcloud services enable endpoints.googleapis.com
Also enable your Endpoints service:
gcloud services enable ENDPOINTS_SERVICE_NAME
To determine the ENDPOINTS_SERVICE_NAME you can either:
After deploying the Endpoints configuration, go to the Endpoints page in the Cloud console. The list of possible ENDPOINTS_SERVICE_NAME are shown under the Service name column.
For OpenAPI, the ENDPOINTS_SERVICE_NAME is what you specified in the
host
field of your OpenAPI spec. For gRPC, the ENDPOINTS_SERVICE_NAME is what you specified in thename
field of your gRPC Endpoints configuration.
For more information about the gcloud
commands, see
gcloud
services.
Building a new ESPv2 image
Build the Endpoints service config into a new ESPv2 docker image. You will later deploy this image onto the reserved Cloud Run service.
To build the service config into a new ESPv2 docker image:
Download this script to your local machine where the gcloud CLI is installed.
Run the script with the following command:
chmod +x gcloud_build_image
./gcloud_build_image -s CLOUD_RUN_HOSTNAME \ -c CONFIG_ID -p ESP_PROJECT_ID
For CLOUD_RUN_HOSTNAME, specify the hostname of the URL that you reserved above in Reserving a Cloud Run hostname. Don't include the protocol identifier,
https://
.For example:
chmod +x gcloud_build_image
./gcloud_build_image -s gateway-12345-uc.a.run.app \ -c 2019-02-01r0 -p your-project-id
-
The script uses the
gcloud
command to download the service config, build the service config into a new ESPv2 image, and upload the new image to your project container registry. The script automatically uses the latest release of ESPv2, denoted by the ESP_VERSION in the output image name. The output image is uploaded to:gcr.io/ESP_PROJECT_ID/endpoints-runtime-serverless:ESP_VERSION-CLOUD_RUN_HOSTNAME-CONFIG_ID
For example:
gcr.io/your-project-id/endpoints-runtime-serverless:2.14.0-gateway-12345-uc.a.run.app-2019-02-01r0"
Deploying the ESPv2 container
Deploy the ESPv2 Cloud Run service with the new image you built above. Replace CLOUD_RUN_SERVICE_NAME with the same Cloud Run service name you used when you originally reserved the hostname above in Reserving a Cloud Run hostname:
gcloud run deploy CLOUD_RUN_SERVICE_NAME \ --image="gcr.io/ESP_PROJECT_ID/endpoints-runtime-serverless:ESP_VERSION-CLOUD_RUN_HOSTNAME-CONFIG_ID" \ --allow-unauthenticated \ --platform managed \ --project=ESP_PROJECT_ID
If you want to configure Endpoints to use additional ESPv2 startup options, such as enabling CORS, you can pass the arguments in the
ESPv2_ARGS
environment variable:gcloud run deploy CLOUD_RUN_SERVICE_NAME \ --image="gcr.io/ESP_PROJECT_ID/endpoints-runtime-serverless:ESP_VERSION-CLOUD_RUN_HOSTNAME-CONFIG_ID" \ --set-env-vars=ESPv2_ARGS=--cors_preset=basic \ --allow-unauthenticated \ --platform managed \ --project ESP_PROJECT_ID
For more information and examples on setting the
ESPv2_ARGS
environment variable, including the list of available options and information on how to specify multiple options, see Extensible Service Proxy V2 Beta flags.Grant ESPv2 permission to call Service Management and Service Control.
- In the Google Cloud console, go to the Cloud Run page.
- You can see the Cloud Run instance you deployed and the service account associated with it.
- Grant required permissions to the service account:
Grant ESPv2 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 and FUNCTION_REGION with the region the function is
deployed to. If you are using the function created in the
Quickstart: Using the Google Cloud CLI,
then use
helloGET
as the name. - Replace ESP_PROJECT_NUMBER with the
project number of the project that you created for
ESPv2. One way to find this is to go to the
IAM page in the Google Cloud console and find the
Default compute service account, which is the service account used in
the
member
flag.
gcloud functions add-iam-policy-binding FUNCTION_NAME \ --region FUNCTION_REGION \ --member "serviceAccount:ESP_PROJECT_NUMBER-compute@developer.gserviceaccount.com" \ --role "roles/cloudfunctions.invoker" \ --project FUNCTIONS_PROJECT_ID
- Replace FUNCTION_NAME with the name of your
function and FUNCTION_REGION with the region the function is
deployed to. If you are using the function created in the
Quickstart: Using the Google Cloud CLI,
then use
gcloud projects add-iam-policy-binding PROJECT_NAME \ --member "serviceAccount:SERVICE_ACCOUNT" \ --role roles/servicemanagement.serviceControllerFor more information, see What are roles and permissions?
For more information, see Managing Access via IAM.
Sending requests to the API
This section shows how to send requests to your API.
- 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 valueapplication/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
View the activity graphs for your API on the Endpoints > Service page in the Google Cloud console.
View Endpoints activity graphs
It may take a few moments for the request to be reflected in the graphs.
Look at the request logs for your API on the Logs Explorer 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 Google Cloud account for the resources used on this page, follow these steps.
See Deleting an API and API instances for information on stopping the services used by this tutorial.