本教學課程說明如何設定及部署範例 API 和可擴充服務 Proxy V2 (ESPv2),上述元件會在受管理執行個體群組 (MIG) 的預先建立 Docker 容器中運作。
此文使用 OpenAPI 規範說明範例程式碼的 REST API。本教學課程也會說明如何建立 API 金鑰並用於對 API 的要求中。
如需 Cloud Endpoints 的總覽資訊,請參閱關於 Endpoints 和 Endpoints 架構。
目標
請根據以下的主要工作清單,逐步進行本教學課程的各個步驟。您必須完成所有工作才能成功傳送要求至 API。- 設定 Google Cloud 專案。請參閱「事前準備」。
- 下載範例程式碼。請參閱取得範例程式碼。
- 設定
openapi.yaml檔案,這個檔案用於設定 Endpoints。請參閱設定 Endpoints 一節。 - 部署 Endpoints 設定以建立 Endpoints 服務。請參閱部署 Endpoints 設定一節。
- 在代管執行個體群組 (MIG) 後端部署 API 和 ESPv2。請參閱部署 API 後端一節。
- 使用 IP 位址傳送要求至 API。詳情請參閱使用 IP 位址傳送要求一節。
- 為範例 API 設定 DNS 記錄。請參閱為 Endpoints 設定 DNS 一節。
- 使用完整的網域名稱將要求傳送至 API,請參閱使用 FQDN 傳送要求一節。
- 追蹤 API 活動。請參閱追蹤 API 活動一節。
- 避免系統向您的 Google Cloud 帳戶收取費用。請參閱「清除所用資源」一節。
費用
在本文件中,您會使用下列 Google Cloud的計費元件:
您可以使用 Pricing Calculator,根據預測用量估算費用。
完成本文所述工作後,您可以刪除建立的資源,避免繼續計費,詳情請參閱「清除所用資源」。
事前準備
事前準備
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
- 記下專案 ID,後續步驟將會用到。
-
您需要一個可以將要求傳送至範例 API 的應用程式。
- Linux 和 macOS 使用者:本教學課程提供了使用
curl的範例,這項工具通常已預先安裝於您的作業系統。如果您尚未安裝curl,可以前往curl的版本與下載頁面下載這項工具。 - Windows 使用者:本教學課程提供了使用
Invoke-WebRequest的範例,PowerShell 3.0 以上版本均支援這項工具。
- Linux 和 macOS 使用者:本教學課程提供了使用
- 下載 Google Cloud CLI。
-
更新 gcloud CLI 並安裝 Endpoints 元件。
gcloud components update
-
確認 Google Cloud CLI (
gcloud) 已取得授權,可存取您在 Google Cloud上的資料與服務: 在開啟的新瀏覽器分頁中選取一個帳戶。gcloud auth login
-
將預設專案設為您的專案 ID。
gcloud config set project YOUR_PROJECT_ID
將 YOUR_PROJECT_ID 替換為專案 ID。如果您有其他 Google Cloud 專案,並想使用
gcloud加以管理,請參閱管理 gcloud CLI 設定。
完成本文所述工作後,您可以刪除建立的資源,避免繼續計費,詳情請參閱「清除所用資源」一節。
下載範例程式碼
將範例程式碼下載至本機電腦。
如何複製或下載範例 API:
- 將範例應用程式存放區複製到您的本機電腦:
git clone https://github.com/GoogleCloudPlatform/java-docs-samples
或者,您也可以選擇下載範例 ZIP 檔案,然後再解壓縮。
- 前往包含範例程式碼的目錄:
cd java-docs-samples/endpoints/getting-started
如何複製或下載範例 API:
- 將範例應用程式存放區複製到您的本機電腦:
git clone https://github.com/GoogleCloudPlatform/python-docs-samples
或者,您也可以選擇下載範例 ZIP 檔案,然後再解壓縮。
- 前往包含範例程式碼的目錄:
cd python-docs-samples/endpoints/getting-started
如何複製或下載範例 API:
- 確定您已設定
GOPATH環境變數。 - 將範例應用程式存放區複製到您的本機電腦:
go get -d github.com/GoogleCloudPlatform/golang-samples/endpoints/getting-started
- 前往包含範例程式碼的目錄:
cd $GOPATH/src/github.com/GoogleCloudPlatform/golang-samples/endpoints/getting-started
如何複製或下載範例 API:
- 將範例應用程式存放區複製到您的本機電腦:
git clone https://github.com/GoogleCloudPlatform/php-docs-samples
或者,您也可以選擇下載範例 ZIP 檔案,然後再解壓縮。
- 前往包含範例程式碼的目錄:
cd php-docs-samples/endpoints/getting-started
如何複製或下載範例 API:
- 將範例應用程式存放區複製到您的本機電腦:
git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples
或者,您也可以選擇下載範例 ZIP 檔案,然後再解壓縮。
- 前往包含範例程式碼的目錄:
cd ruby-docs-samples/endpoints/getting-started
如何複製或下載範例 API:
- 將範例應用程式存放區複製到您的本機電腦:
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
或者,您也可以選擇下載範例 ZIP 檔案,然後再解壓縮。
- 前往包含範例程式碼的目錄:
cd nodejs-docs-samples/endpoints/getting-started
設定 Endpoints
您必須提供符合 OpenAPI 2.0 或 OpenAPI 3.x 的 OpenAPI 文件,此文件須說明您應用程式的介面以及所有驗證需求。詳情請參閱「支援的 OpenAPI 版本」。
此外,您也必須加入內含各應用程式網址的 Google 專用欄位,這樣 ESPv2 才能獲得叫用應用程式所需的資訊。如果您還不熟悉 OpenAPI,請參閱 OpenAPI 總覽瞭解詳情。
OpenAPI 2.0
如要使用 OpenAPI 2.0 規格設定 Endpoints,可以使用下載範例程式碼的 endpoints/getting-started 目錄中提供的 openapi.yaml 檔案。
OpenAPI 2.0 規格的內容應與下列內容類似:
swagger: "2.0" info: description: "A simple Google Cloud Endpoints API example." title: "Endpoints Example" version: "1.0.0" host: "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog" consumes: - "application/json" produces: - "application/json" schemes: # Uncomment the next line if you configure SSL for this API. # - "https" - "http" paths: /echo: post: description: "Echo back a given message." operationId: "echo" produces: - "application/json" responses: 200: description: "Echo" schema: $ref: "#/definitions/echoMessage" parameters: - description: "Message to echo" in: body name: message required: true schema: $ref: "#/definitions/echoMessage" security: - api_key: [] /auth/info/googlejwt: get: description: "Returns the requests' authentication information." operationId: "auth_info_google_jwt" produces: - "application/json" responses: 200: description: "Authenication info." schema: $ref: "#/definitions/authInfoResponse" security: - api_key: [] google_jwt: [] /auth/info/googleidtoken: get: description: "Returns the requests' authentication information." operationId: "authInfoGoogleIdToken" produces: - "application/json" responses: 200: description: "Authentication info." schema: $ref: "#/definitions/authInfoResponse" security: - api_key: [] google_id_token: [] definitions: echoMessage: type: "object" properties: message: type: "string" authInfoResponse: properties: id: type: "string" email: type: "string" securityDefinitions: # This section configures basic authentication with an API key. api_key: type: "apiKey" name: "key" in: "query" # This section configures authentication using Google API Service Accounts # to sign a json web token. This is mostly used for server-to-server # communication. google_jwt: authorizationUrl: "" flow: "implicit" type: "oauth2" # This must match the 'iss' field in the JWT. x-google-issuer: "jwt-client.endpoints.sample.google.com" # Update this with your service account's email address. x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/jwk/YOUR_SERVICE_ACCOUNT_EMAIL" # This must match the "aud" field in the JWT. You can add multiple # audiences to accept JWTs from multiple clients. x-google-audiences: "echo.endpoints.sample.google.com" # This section configures authentication using Google OAuth2 ID Tokens. # ID Tokens can be obtained using OAuth2 clients, and can be used to access # your API on behalf of a particular user. google_id_token: authorizationUrl: "" flow: "implicit" type: "oauth2" x-google-issuer: "https://accounts.google.com" x-google-jwks_uri: "https://www.googleapis.com/oauth2/v3/certs" # Your OAuth2 client's Client ID must be added here. You can add # multiple client IDs to accept tokens from multiple clients. x-google-audiences: "YOUR_CLIENT_ID"
OpenAPI 3.x
如要使用 OpenAPI 3.x 規格設定 Endpoints,可以取代下載範例程式碼的 endpoints/getting-started 目錄中 openapi.yaml 檔案的內容:
- 在文字編輯器中開啟
openapi.yaml,並將內容替換為下列程式碼:openapi: 3.0.4 info: description: "A simple Google Cloud Endpoints API example." title: "Endpoints Example" version: "1.0.0" servers: - url: "http://echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog" x-google-endpoint: {} paths: "/echo": post: description: "Echo back a given message." operationId: "echo" requestBody: description: "Message to echo" required: true content: "application/json": schema: $ref: "#/components/schemas/echoMessage" responses: '200': description: "Echo" content: "application/json": schema: $ref: "#/components/schemas/echoMessage" security: - api_key: [] "/auth/info/googlejwt": get: description: "Returns the requests' authentication information." operationId: "auth_info_google_jwt" responses: '200': description: "Authentication info." content: "application/json": schema: $ref: "#/components/schemas/authInfoResponse" security: - api_key: [] google_jwt: [] "/auth/info/googleidtoken": get: description: "Returns the requests' authentication information." operationId: "authInfoGoogleIdToken" responses: '200': description: "Authentication info." content: "application/json": schema: $ref: "#/components/schemas/authInfoResponse" security: - api_key: [] google_id_token: [] components: schemas: echoMessage: type: "object" properties: message: type: "string" authInfoResponse: properties: id: type: "string" email: type: "string" securitySchemes: api_key: type: "apiKey" name: "key" in: "query" google_jwt: type: "oauth2" flows: implicit: authorizationUrl: "" scopes: {} x-google-auth: issuer: "jwt-client.endpoints.sample.google.com" jwksUri: "https://www.googleapis.com/service_accounts/v1/jwk/YOUR_SERVICE_ACCOUNT_EMAIL" audiences: "echo.endpoints.sample.google.com" google_id_token: type: "oauth2" flows: implicit: authorizationUrl: "" scopes: {} x-google-auth: issuer: "https://accounts.google.com" jwksUri: "https://www.googleapis.com/oauth2/v3/certs" audiences: - "YOUR_CLIENT_ID"
- 儲存
openapi.yaml的新內容。
本教學課程會使用 OpenAPI 規格的 Google 專屬擴充功能,讓您設定服務名稱。指定服務名稱的方法取決於您使用的 OpenAPI 規格版本。
OpenAPI 2.0
使用 host 欄位指定服務名稱:
host: echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog
如要設定 Endpoints:
- 開啟
openapi.yaml檔案。 - 在
host欄位中,將 YOUR_PROJECT_ID 替換為您的 Google Cloud 專案 ID。 - 儲存
openapi.yaml檔案。
OpenAPI 3.x
在 servers 物件中使用 url 欄位指定服務名稱:
servers: - url: https://echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog x-google-endpoint: {}
如要設定 Endpoints:
- 開啟
openapi.yaml檔案。 - 如果
openapi.yaml檔案有host欄位,請移除該欄位。 - 新增
servers物件,如下所示。 - 在
url欄位中,將 YOUR_PROJECT_ID 替換為您的 Google Cloud 專案 ID。 - 儲存
openapi.yaml檔案。
完成下列的所有設定步驟之後,您就能使用 IP 位址成功將要求傳送至範例 API。請參閱「為 Endpoints 設定 DNS」一節,瞭解如何將 echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog 設為完整的網域名稱 (FQDN)。
部署 Endpoints 設定
如要部署 Endpoints 設定,請使用 gcloud endpoints
services deploy 指令。這個指令會使用 Service Management 建立代管服務。
如何部署 Endpoints 設定:
- 確認您位於
openapi.yaml設定檔所在的目錄。 - 上傳設定並建立代管服務:
gcloud endpoints services deploy openapi.yaml
接著,gcloud 指令會呼叫 Service Management API,並使用您在 openapi.yaml 檔案 host 或 servers.url 欄位中指定的名稱建立代管服務。Service Management 會依據 openapi.yaml 檔案中的設定建立服務。變更 openapi.yaml 時,您必須重新部署檔案才能更新 Endpoints 服務。
Service Management 在建立和設定服務時,會輸出資訊至終端機。您可以放心忽略 openapi.yaml 檔案中路徑不需要 API 金鑰的警告。完成服務設定程序之後,Service Management 會顯示含有服務設定 ID 與服務名稱的訊息,類似於以下內容:
Service Configuration [2017-02-13r0] uploaded for service [echo-api.endpoints.example-project-12345.cloud.goog]
在上方的範例中,2017-02-13r0 是服務設定 ID,echo-api.endpoints.example-project-12345.cloud.goog 則為 Endpoints 服務。服務設定 ID 是由一個日期戳記和一個修訂版本編號所組成。如果您在同一天再次部署 openapi.yaml 檔案,服務設定 ID 中的修訂版本編號就會遞增。您可以在 Google Cloud 主控台的「Endpoints」 >「Services」(服務) 頁面中查看 Endpoints 服務設定。
如果您收到錯誤訊息,請參閱 Endpoints 設定部署疑難排解一文。
檢查必要服務
Endpoints 和 ESP 至少需要啟用下列 Google 服務:| 名稱 | 標題 |
|---|---|
servicemanagement.googleapis.com |
Service Management API |
servicecontrol.googleapis.com |
Service Control API |
在大多數情況下,gcloud endpoints services deploy 指令會啟用這些必要服務。不過在以下情況中,即便您成功執行 gcloud 指令,還是無法啟用必要服務:
您使用 Terraform 之類的第三方應用程式,而其中未包含這些服務。
您已將 Endpoints 設定部署至現有Google Cloud 專案,但在專案中已明確停用這些服務。
使用下列指令確認必要服務已啟用:
gcloud services list
如果必要的服務並未列出,請執行下列指令加以啟用:
gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.com同時啟用 Endpoints 服務:
gcloud services enable ENDPOINTS_SERVICE_NAME
如要判斷 ENDPOINTS_SERVICE_NAME,您可以採取下列任一做法:
部署 Endpoints 設定後,請前往 Cloud 控制台的「Endpoints」頁面。「服務名稱」欄下方會顯示可能的 ENDPOINTS_SERVICE_NAME 清單。
如果是 OpenAPI,ENDPOINTS_SERVICE_NAME 是您在 OpenAPI 規格的
host欄位中指定的內容。如果是 gRPC,ENDPOINTS_SERVICE_NAME 是您在 gRPC Endpoints 設定的name欄位中指定的內容。
如要進一步瞭解 gcloud 指令,請參閱 gcloud 服務。
部署 API 後端
建立執行個體範本
建立範本,以便用來建立一組 VM 執行個體。每個利用範本建立的執行個體,都會啟動 ESPv2 和後端應用程式伺服器。
前往 Google Cloud 控制台的「Instance templates」(執行個體範本) 頁面。
點選「建立執行個體範本」。
在「Name」(名稱) 下方輸入
load-balancing-espv2-template。在「Machine configuration」(機器設定) 下,將「Machine type」(機器類型) 設為
e2-micro。在「Boot disk」(開機磁碟) 下,將「Image」(映像檔) 設為
Container Optimized OS stable version。在「Firewall」(防火牆) 下,選取 [Allow HTTP traffic] (允許 HTTP 流量)。
按一下 [Management, security, disks, networking, sole tenancy] (管理、安全性、磁碟、網路、單獨租用) 即可顯示進階設定。
按一下 [Management] (管理) 分頁標籤。在「Automation」(自動) 下方輸入以下開機指令碼:請記得更新「ENDPOINTS_SERVICE_NAME」。
sudo docker network create --driver bridge esp_net sudo docker run \ --detach \ --name=echo \ --net=esp_net \ gcr.io/google-samples/echo-python:1.0 sudo docker run \ --detach \ --name=esp \ --publish=80:9000 \ --net=esp_net \ gcr.io/endpoints-release/endpoints-runtime:2 \ --service=ENDPOINTS_SERVICE_NAME \ --rollout_strategy=managed \ --listener_port=9000 \ --healthz=/healthz \ --backend=echo:8080
執行個體啟動時,指令碼會取得、安裝並啟動 Echo 應用程式伺服器和 ESPv2 Proxy 伺服器。
點選「建立」。
請等候範本建立完成後再繼續操作。
建立地區代管執行個體群組
如要執行應用程式,請使用執行個體範本建立地區代管執行個體群組:
前往 Google Cloud 控制台的「Instance groups」(執行個體群組) 頁面。
點選「建立執行個體群組」。
在「Name」(名稱) 下方輸入
load-balancing-espv2-group。在「Location」(位置) 下,選取 [Multiple zones] (多區域)。
在「Region」(地區) 下,選取 [us-central1]。
按一下 [Configure zones] (設定區域) 下拉式選單,即可查看「Zones」(區域)。選取下列區域:
- us-central1-b
- us-central1-c
- us-central1-f
在「Instance template」(執行個體範本) 下,選取
load-balancing-espv2-template。在「Autoscaling」(自動調度資源) 下方,選取「Don't autoscale」(不要自動調整資源配置)。
將「Number of instances」(執行個體數量) 設為
3。在「Instance redistribution」(執行個體重新分配) 下,選取 [On] (啟用)。
在「Autohealing」(自動修復) 與「Health check」(健康狀態檢查) 下,選取 [No health check] (不執行健康狀態檢查)。
按一下 [Create] (建立),系統就會將您重新導向至「Instance groups」(執行個體群組) 頁面。
建立負載平衡器
本節說明建立全域負載平衡器的所需步驟,藉此將 HTTP 流量導向執行個體群組。這類負載平衡器會使用前端接收連入流量,也會透過後端將這類流量分配至健康狀態良好的執行個體。負載平衡器是由多個元件組成,因此這項工作分成下列幾個部分:
- 後端設定
- 前端設定
- 檢查並完成
完成所有步驟以建立負載平衡器。
前往 Google Cloud 控制台的「Create a load balancer」(建立負載平衡器) 頁面。
在「應用程式負載平衡器 (HTTP/S)」區段中,按一下「開始設定」。
在「Internet facing or internal only」(連結網際網路或僅限內部) 下,選取 [From Internet to my VMs] (從網際網路到我的 VM),然後按一下 [Continue] (繼續)。
在負載平衡器的「Name」(名稱) 中輸入
espv2-load-balancer。
後端設定
- 在「Create global external Application Load Balancer」(建立全域外部應用程式負載平衡器) 頁面的左側面板中,按一下「Backend configuration」(後端設定)。
- 按一下 [Create or select backend services & backend buckets] (建立或選擇後端服務與後端值區),以開啟下拉式選單。按一下 [Backend services] (後端服務),然後按一下 [Create a backend service] (建立後端服務)。
- 在新視窗中,在後端應用程式的「Name」(名稱) 中輸入
espv2-backend。 - 將「Instance group」(執行個體群組) 設為
load-balancing-espv2-group。 - 將「Port numbers」(通訊埠編號) 設為
80,即可在負載平衡器和執行個體群組之間傳送 HTTP 流量。 - 在「Balancing mode」(平衡模式) 下,選取 [Utilization] (使用率)。
- 按一下 [Done] (完成) 即可建立後端。
針對負載平衡器的後端建立健康狀態檢查:
- 在「Health check」(健康狀態檢查) 下的下拉式選單中,選取 [Create a health check] (建立健康狀態檢查) (或 [Create another health check] (建立另一個健康狀態檢查))。系統隨即會開啟新視窗。
- 在新視窗的「Name」(名稱) 下方輸入
espv2-load-balancer-check。 - 將「Protocol」(通訊協定) 設為 [HTTP]。
- 在「Port」(通訊埠) 下方輸入
80。 - 在本教學課程中,請將「Request path」(要求路徑) 設為
/healthz,也就是 ESPv2 設定要回應的路徑。 設定下列「Health criteria」(健康狀態判定條件):
- 將「Check interval」(檢查時間間隔) 設定為
3秒。這項設定會定義從一次探測開始到下一次探測開始之間的時間間隔。 - 將「Timeout」(逾時間隔) 設定為
3秒。這項設定會定義 Google Cloud 等待探測回應的時間長度。這個值必須小於或等於檢查時間間隔。 - 將「Healthy Threshold」(良好健康狀態判定門檻) 設為連續
2次通過健康狀態檢查。這項設定會定義將執行個體的健康狀態判定為良好時,必須成功執行的連續探測次數。 - 將「Unhealthy Threshold」(不良健康狀態判定門檻) 設為連續
2次健康狀態檢查未通過。這項設定會定義將執行個體的健康狀態判定為不良時,探測必須連續失敗的次數。
- 將「Check interval」(檢查時間間隔) 設定為
按一下 [Save and continue] (儲存並繼續) 以建立健康狀態檢查。
按一下 [Create] (建立) 即可建立後端服務。
前端設定
- 在「建立全域外部應用程式負載平衡器」頁面的左側面板中,按一下「前端設定」。
- 在「Frontend configuration」(前端設定) 頁面的「Name」(名稱) 下方輸入
espv2-ipv4-frontend。 - 將「Protocol」(通訊協定) 設為
HTTP。 - 將「Port」(通訊埠) 設為
80。 - 按一下 [Done] (完成) 即可建立前端。
檢查並完成
先驗證負載平衡設定,然後再建立負載平衡器:
- 在「建立全域外部應用程式負載平衡器」頁面的左側面板中,按一下「檢查並完成」。
在「Review and finalize」(檢查並完成) 頁面上,確認下列「Backend」(後端) 設定:
- 「Backend service」(後端服務) 為
espv2-backend。 - 「Endpoint protocol」(端點通訊協定) 為
HTTP。 - 「Health check」(健康狀態檢查) 為
espv2-load-balancer-check。 - 「Instance group」(執行個體群組) 為
load-balancing-espv2-group。
- 「Backend service」(後端服務) 為
在同一個頁面上,確認「Frontend」(前端) 使用「Protocol」(通訊協定) 為
HTTP的 IP 位址。
在「Create global external Application Load Balancer」(建立全域外部應用程式負載平衡器) 頁面的左側面板中,按一下「Create」(建立),完成負載平衡器的建立作業。
您可能需要稍候幾分鐘,等待系統完成負載平衡器的建立作業。
負載平衡器建立完成後,請在「Load Balancer」(負載平衡器)頁面中找出 IP 位址。
使用 IP 位址傳送要求
範例 API 和 ESPv2 在已部署的後端上運作之後,您就可以從本機電腦將要求傳送至 API。
建立 API 金鑰並設定環境變數
範例程式碼需要 API 金鑰。為了簡化要求,請設定 API 金鑰的環境變數。
在您用於 API 的 Google Cloud 專案中,在 API 憑證頁面上建立 API 金鑰。如要在其他 Google Cloud 專案中建立 API 金鑰,請參閱「在 Google Cloud 專案中啟用 API」。
- 按一下 [Create credentials] (建立憑證),然後選取 [API key] (API 金鑰)。
- 將金鑰複製到剪貼簿。
- 按一下 [Close] (關閉)。
- 在本機電腦中貼上 API 金鑰,以便指派給環境變數:
- 在 Linux 或 macOS 中:
export ENDPOINTS_KEY=AIza... - 在 Windows PowerShell 中:
$Env:ENDPOINTS_KEY="AIza..."
- 在 Linux 或 macOS 中:
傳送要求
Linux 或 mac OS
使用 curl,透過先前設定的 ENDPOINTS_KEY 環境變數傳送 HTTP 要求。將 IP_ADDRESS 替換為您的執行個體外部 IP 位址。
curl --request POST \ --header "content-type:application/json" \ --data '{"message":"hello world"}' \ "http://IP_ADDRESS:80/echo?key=${ENDPOINTS_KEY}"
在上方的 curl 中:
--data選項會指定要發布至 API 的資料。--header選項會指定資料採用 JSON 格式。
PowerShell
使用 Invoke-WebRequest,透過先前設定的 ENDPOINTS_KEY 環境變數傳送 HTTP 要求。將 IP_ADDRESS 替換為您的執行個體外部 IP 位址。
(Invoke-WebRequest -Method POST -Body '{"message": "hello world"}' ` -Headers @{"content-type"="application/json"} ` -URI "http://IP_ADDRESS:80/echo?key=$Env:ENDPOINTS_KEY").Content
在上述範例中,前兩行的結尾為倒引號。當您將範例貼到 PowerShell 中時,請確保倒引號後面沒有空格。 如要瞭解範例要求中使用的選項,請參閱 Microsoft 說明文件中的 Invoke-WebRequest。
第三方應用程式
您可以使用諸如 Chrome 瀏覽器擴充功能 Postman 等第三方應用程式,傳送要求:
- 選取
POST做為 HTTP 動詞。 - 選取
content-type鍵和application/json值做為標頭。 - 輸入以下內文:
{"message":"hello world"} -
在網址中使用實際的 API 金鑰,而非環境變數。例如:
http://192.0.2.0:80/echo?key=AIza...
API 會回應您傳送的訊息,並傳回以下內容:
{
"message": "hello world"
}
如果您未取得成功的回應,請參閱排解回應錯誤一文。
您已在 Endpoints 中部署並測試了 API!
為 Endpoints 設定 DNS
API 的 Endpoints 服務名稱位於 .endpoints.YOUR_PROJECT_ID.cloud.goog 網域,因此您只需要略為調整 openapi.yaml 檔案的設定,即可將該網域當做完整的網域名稱 (FQDN)。這樣一來,您就能使用 echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog (而非 IP 位址) 將要求傳送至範例 API。
如何設定 Endpoints DNS:
OpenAPI 2.0
- 開啟 OpenAPI 設定檔
openapi.yaml,並在檔案最上層新增x-google-endpoints屬性 (請勿使用縮排或巢狀結構),如以下程式碼片段所示:host: "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog" x-google-endpoints: - name: "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog" target: "IP_ADDRESS" - 在
name屬性中,將 YOUR_PROJECT_ID 替換為您的專案 ID。 - 在
target屬性中,將 IP_ADDRESS 替換為您向範例 API 傳送要求時使用的 IP 位址。 - 將更新的 OpenAPI 設定檔部署至 Service Management:
gcloud endpoints services deploy openapi.yaml
OpenAPI 3.x
- 開啟 OpenAPI 設定檔
openapi.yaml,並在檔案最上層新增servers.url屬性 (請勿使用縮排或巢狀結構),如以下程式碼片段所示:servers: - url: "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog" x-google-endpoint: target: "IP_ADDRESS" - 在
name屬性中,將 YOUR_PROJECT_ID 替換為您的專案 ID。 - 在
target屬性中,將 IP_ADDRESS 替換為您向範例 API 傳送要求時使用的 IP 位址。 - 將更新的 OpenAPI 設定檔部署至 Service Management:
gcloud endpoints services deploy openapi.yaml
舉例來說,假設 openapi.yaml 檔案的設定如下:
OpenAPI 2.0
host: "echo-api.endpoints.example-project-12345.cloud.goog" x-google-endpoints: - name: "echo-api.endpoints.example-project-12345.cloud.goog" target: "192.0.2.1"
OpenAPI 3.x
servers:
- url: "echo-api.endpoints.example-project-12345.cloud.goog"
x-google-endpoint:
target: "192.0.2.1"您使用前述的 gcloud 指令部署 openapi.yaml 檔案時,Service Management 會建立 DNS A 記錄 echo-api.endpoints.my-project-id.cloud.goog,這個記錄會解析為目標 IP 位址 192.0.2.1。新的 DNS 設定可能需要幾分鐘才會生效。
設定安全資料傳輸層 (SSL)
如要進一步瞭解如何設定 DNS 和安全資料傳輸層 (SSL),請參閱啟用 Endpoints 的安全資料傳輸層 (SSL) 一文。
使用 FQDN 傳送要求
為範例 API 設定 DNS 記錄之後,請使用 FQDN (將 YOUR_PROJECT_ID 替換為您的專案 ID) 與先前設定的 ENDPOINTS_KEY 環境變數向 API 傳送要求:
- 在 Linux 或 mac OS 中:
curl --request POST \ --header "content-type:application/json" \ --data '{"message":"hello world"}' \ "http://echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog:80/echo?key=${ENDPOINTS_KEY}"
- 在 Windows PowerShell 中:
(Invoke-WebRequest -Method POST -Body '{"message": "hello world"}' -Headers @{"content-type"="application/json"} -URI "http://echo-api.endpoints.[YOUR_PROJECT_ID].cloud.goog:80/echo?key=$Env:ENDPOINTS_KEY").Content
追蹤 API 活動
如要追蹤 API 活動,請執行下列步驟:
- 在「Endpoints」>「Services」(服務) 頁面中查看 API 的活動圖表。
要求可能需要一些時間才能反映在圖表中。 - 在「Logs Explorer」(記錄檔探索工具) 頁面中查看您的 API 要求記錄。
清除所用資源
為避免因為本教學課程所用資源,導致系統向 Google Cloud 收取費用,請刪除含有相關資源的專案,或者保留專案但刪除個別資源。
確認 gcloud CLI (
gcloud) 已取得授權,可存取您在 Google Cloud上的資料與服務:gcloud auth login輸入下列指令,以顯示 Google Cloud專案的專案 ID:
gcloud projects list使用在上一個步驟中顯示的專案 ID,將預設Google Cloud 專案設為您的應用程式所屬專案:
gcloud config set project [YOUR_PROJECT_ID]取得 Google Cloud 專案中所有代管服務的名稱:
gcloud endpoints services list從 Service Management 中刪除該服務。將
SERVICE_NAME替換為您要移除的服務名稱。gcloud endpoints services delete SERVICE_NAME
執行
gcloud endpoints services delete並不會立即刪除代管服務。Service Management 會先將該代管服務停用 30 天,在這段期間內您可以視需要將其還原。30 天後,Service Management 就會永久刪除該代管服務。前往「Load Balancer」(負載平衡器) 頁面。
刪除負載平衡器
espv2-load-balancer,包括後端服務espv2-backend和健康狀態檢查espv2-load-balancer-check。前往「Instance Groups」(執行個體群組) 頁面。
刪除「
load-balancing-espv2-group」前往「執行個體範本」頁面。
前往「Instance Templates」(執行個體範本)
刪除
load-balancing-espv2-template。