07 - Google Cloud API Gateway¶
In dieser Aufgabe werden wir ein API Gateway vor eine Cloud Run Function schalten, die über einen HTTP-Trigger erreichbar ist.
Schritt 1: Google APIs aktivieren¶
gcloud services enable apigateway.googleapis.com
gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.com
Schritt 2: Node.js-Projekt anlegen¶
Erstellen Sie ein neues Verzeichnis und initialisieren Sie ein Node.js-Projekt.
mkdir api-gateway
cd api-gateway
npm init -y
Installieren Sie das Functions Framework.
npm install --save @google-cloud/functions-framework
Schritt 3: Funktion erstellen¶
Erstellen Sie im Verzeichnis api-gateway eine Datei index.js
mit folgendem Code:
const functions = require('@google-cloud/functions-framework');
functions.http('helloGET', (req, res) => {
res.send('Hello World!');
});
Schritt 4: Function deployen¶
Deployen Sie die Funktion in die Google Cloud.
gcloud functions deploy nodejs-http-function \
--gen2 \
--runtime=nodejs24 \
--source=. \
--entry-point=helloGET \
--trigger-http \
--region europe-west1
Notieren Sie sich die URL der deployten Funktion aus der Ausgabe.
Schritt 5: API erstellen¶
Die API wird mit folgendem Befehl angelegt:
gcloud api-gateway apis create helloworldapi
Informationen über die neue API lassen sich so anzeigen:
gcloud api-gateway apis describe helloworldapi
Schritt 6: API konfigurieren¶
Erstellen Sie eine Datei api.yaml mit folgender
OpenAPI v2-Spezifikation. Denken Sie daran, den GCF-Endpunkt
einzutragen, der in Schritt 4 erzeugt wurde.
# api.yaml
swagger: '2.0'
info:
title: myapi 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://REGION-PROJECT.cloudfunctions.net/nodejs-http-function
responses:
'200':
description: A successful response
schema:
type: string
Erstellen Sie nun die API-Konfiguration. Für den Backend-Service-Account brauchen wir die Projektnummer, die wir mit einem gcloud-Befehl auslesen.
export PROJECT_NUMBER=$(gcloud projects describe \
$(gcloud config get-value project) \
--format="value(projectNumber)")
gcloud api-gateway api-configs create my-config \
--api=helloworldapi --openapi-spec=api.yaml \
--backend-auth-service-account \
${PROJECT_NUMBER}-compute@developer.gserviceaccount.com
Schritt 7: Gateway bereitstellen¶
Nachdem die Konfiguration bereit ist, erstellen wir das eigentliche Gateway.
gcloud api-gateway gateways create my-gateway \
--api=helloworldapi --api-config=my-config \
--location=europe-west1
Danach lässt sich die URL wie folgt auslesen:
gcloud api-gateway gateways describe my-gateway \
--location europe-west1
Hängen Sie /hello an die URL an und rufen Sie sie im Browser auf.
Danach können wir uns noch die Konsole anschauen.