Google Cloud: Building an API with Google Cloud API Gateway

Share At:

How to use Google API Gateway with Cloud Run | by Felipe Martinez | Google  Cloud - Community | Medium

Overview

If you are building a microservice, you need to find a way to expose it. Suppose you are working with Cloud Functions or with Cloud Run. If you want to expose them using a structured and secure API, you should consider using Cloud API Gateway.

Cloud API Gateway is a fully managed, easy-to-use, and secure Google service that allows you to create an API for the workload you need to expose. It offers reduced complexity because it lets you define the API using the Swagger OpenAPI 2.0 standard. Following this standard, you would define the specifics about the method of exposing your workloads, such as the path and the protocol.

In this lab, you will create a Cloud Function, and you will create an API with Cloud API Gateway to expose it.

Learning Objectives

Upon completion of this lab, you will be able to:

  • Create an API definition following the OpenAPI 2.0 standard
  • Expose a workload with an API through Cloud API Gateway

Intended Audience

This lab is intended for:

  • Software engineers that need to expose workloads hosted on Google Cloud
  • Cloud Architects who want to understand how to handle and expose multiple workloads in a structured way

Enable the required APIs

  1. In the Cloud Console, navigate to APIs & Services > Library:
a760c2114e894de5.png

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

api-gw-tile.png

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

enable-api-gw.png

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

2. Change to the directory that contains the Cloud Functions sample code:

cd nodejs-docs-samples/functions/helloworld/

3. To deploy the function with an HTTP trigger, run the following command in the directory containing your function:

gcloud functions deploy helloGET --runtime nodejs10 --trigger-http --allow-unauthenticated

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

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

2. The output should look similar to the URL below where PROJECT_ID is a value specific to your project. To obtain your PROJECT_ID you can run the following command in the Cloud Shell console:

export PROJECT_ID=$(gcloud config get-value project)

3. Visit the URL to invoke the Cloud Function. You should see the message Hello World! as the response:

curl -v https://us-central1-${PROJECT_ID}.cloudfunctions.net/helloGET

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://us-central1-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

Creating a Gateway

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

  1. From the Navigation menu, open the API Gateway page.
api-gateway-side-menu.png
  1. Click Create Gateway.
  2. In the API 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 a new API config.
  • Do the following to upload the openapi2-functions.yaml file previously created.

5. In Cloud Shell, run the following command.

cloudshell download $HOME/openapi2-functions.yaml

The file openapi2-functions.yaml is now downloaded to your local machine.

6. 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 us-central1.
  1. 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.

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 retreive the GATEWAY_URL of the newly created API hosted by API Gateway:
export GATEWAY_URL=$(gcloud api-gateway gateways describe hello-gateway --location us-central1 --format json | jq -r .defaultHostname)

2. Run the following curl command and validate that the response returned is Hello World!.

curl -s -w "\n" https://$GATEWAY_URL/hello

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.
  3. The API key created dialog box displays your newly created key.
create-api-key.png
  1. Copy the API Key by clicking on the copy icon next to the key in the Credentials page.
  1. Store the API Key value in Cloud Shell by running the following command:
export API_KEY=REPLACE_WITH_COPIED_API_KEY
  1. Enable API Key support for your service.
  1. In the Cloud Console, navigate 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.
  1. In Cloud Shell, obtain the name of the managed service you just created using the following command:
gcloud api-gateway apis list --format json | jq -r .[0].managedService | cut -d'/' -f6
  1. In the search bar, enter the Managed Service name of the API you just created. Click the Enable button for the service once displayed.
  1. If you receive a notification like This API is provided by a third-party and it will be visible then click Ok.

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 the openapi2-functions.yaml file created previously as shown below:
# 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://us-central1-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. Download the updated API spec file, you will use it to update the Gateway config in the next step:
cloudshell download $HOME/openapi2-functions.yaml

Create and deploy a new API config to your existing gateway

  1. Open the API Gateway page in Cloud Console. Under the Left Menu > API Gateway.
api-gateway-side-menu.png
  1. Select your API from the list to view details.
  2. Select the Gateways tab.
  3. Select Hello Gateway from the list of available Gateways.
  4. Click on Edit at the top of the Gateway page.
  5. Under API Config change the drop down to Create new API config.
  6. Click Browse in the Upload an API Spec input box and select the openapi2-functions.yaml file.
  7. Enter Hello Config for Display Name.
  8. Select Qwiklabs User Service Account for Select a Service Account.
  9. Click Update.

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 us-central1 --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. 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.
curl -sL -w "\n" $GATEWAY_URL/hello?key=$API_KEY

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

Happy Learning !!!


Share At:
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Back To Top

Contact Us