本教程介绍如何配置和部署在 App Engine 柔性环境中的实例上运行的示例 .NET core API 和 Extensible Service Proxy (ESP)。示例 API 是使用 OpenAPI 规范描述的。本教程还介绍了如何创建 API 密钥,以及如何在向 API 发送请求时使用此密钥。
如需大致了解 Cloud Endpoints,请参阅关于 Endpoints 和 Endpoints 架构。
目标
学习本教程时,请使用以下概要任务列表。为确保请求成功发送到 API,您必须完成所有任务。
- 设置 Google Cloud 项目,安装所需软件,并创建 App Engine 应用。请参阅准备工作。
- 下载示例代码。请参阅获取示例代码。
- 配置
openapi.yaml文件,该文件用于配置 Endpoints。请参阅配置 Endpoints。 - 部署 Endpoints 配置以创建 Endpoints 服务。请参阅部署 Endpoints 配置。
- 将示例 API 和 ESP 部署到 App Engine。请参阅部署 API 后端。
- 向 API 发送请求。请参阅向 API 发送请求。
- 跟踪 API 活动。请参阅跟踪 API 活动。
- 避免您的 Google Cloud 账号产生费用。请参阅清理。
费用
在本文档中,您将使用 Google Cloud的以下收费组件:
如需根据您的预计使用量来估算费用,请使用价格计算器。
完成本文档中描述的任务后,您可以通过删除所创建的资源来避免继续计费。如需了解详情,请参阅清理。
准备工作
准备工作
- 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,您稍后需要用到。
-
本教程需要使用 .NET Core 2.x SDK,您可以将其用于任何文本编辑器。虽然不需要集成开发环境 (IDE),但为了方便起见,我们建议您使用以下 IDE 之一:
- Visual Studio Code,在 macOS、Linux 和 Windows 上运行。如果您使用 Visual Studio Code,还必须安装 .NET Core 2.x。
- Visual Studio 2017 for Windows,其中包含 .NET Core 2.x。如果您使用 Visual Studio 2017,则建议您使用 Google Tools for Visual Studio 插件,该插件在 IDE 内集成了 App Engine 部署。
- Visual Studio for Mac,其中包含 .NET Core 2.x。
您需要一个可以向示例 API 发送请求的应用。本教程提供了一个使用
Invoke-WebRequest的示例,PowerShell 3.0 及更高版本支持该命令。- 下载 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 替换为您的 Google Cloud 项目 ID。 如果您有其他 Google Cloud 项目,并且想使用
gcloud来管理这些项目,请参阅管理 gcloud CLI 配置。 - 选择您要在其中创建 App Engine 应用的区域。运行以下命令以获取区域列表:
gcloud app regions list
- 创建 App Engine 应用。将 YOUR_PROJECT_ID 替换为您的 Google Cloud项目 ID,并将 YOUR_REGION 替换为您要在其中创建 App Engine 应用的区域。
gcloud app create \ --project=YOUR_PROJECT_ID \ --region=YOUR_REGION
获取示例代码
要下载示例 API,请执行以下操作:
以 zip 文件的形式下载示例代码。
将 zip 文件解压缩并切换到
dotnet-docs-samples-master\endpoints\getting-started目录。使用 Visual Studio 打开
GettingStarted.sln,或使用您惯用的编辑器修改endpoints\getting-started\src\IO.Swagger目录中的文件。
配置 Endpoints
您必须拥有基于 OpenAPI 2.0 或 OpenAPI 3.x 的 OpenAPI 文档,该文档描述了您的应用的表面和各项身份验证要求。如需了解详情,请参阅支持的 OpenAPI 版本。
您还需要添加包含各应用的网址的 Google 专属字段,以便 ESPv2 获得调用应用所需的信息。如果您刚接触 OpenAPI,请参阅 OpenAPI 概览了解详情。
OpenAPI 2.0
如需使用 OpenAPI 2.0 规范配置 Endpoints,您可以使用下载的示例代码的 dotnet-docs-samples-master\endpoints\getting-started 目录中提供的 openapi-appengine.yaml 文件。
OpenAPI 2.0 规范的内容应类似于以下内容:
swagger: "2.0" info: description: "A simple Google Cloud Endpoints API example." title: "Endpoints Example" version: "1.0.0" host: "YOUR_PROJECT_ID.appspot.com" consumes: - "application/json" produces: - "application/json" schemes: - "https" 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: "Authentication info." schema: $ref: "#/definitions/authInfoResponse" x-security: - google_jwt: audiences: # This must match the "aud" field in the JWT. You can add multiple # audiences to accept JWTs from multiple clients. - "echo.endpoints.sample.google.com" "/auth/info/googleidtoken": get: description: "Returns the requests' authentication information." operationId: "authInfoGoogleIdToken" produces: - "application/json" responses: 200: description: "Authenication info." schema: $ref: "#/definitions/authInfoResponse" x-security: - google_id_token: audiences: # Your OAuth2 client's Client ID must be added here. You can add # multiple client IDs to accept tokens from multiple clients. - "YOUR-CLIENT-ID" 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 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/v1/certs"
在包含 host 字段的行中,将 YOUR_PROJECT_ID 替换为您的 Google Cloud 项目 ID。
OpenAPI 3.x
如需使用 OpenAPI 3.x 规范配置 Endpoints,您可以替换下载的示例代码的 dotnet-docs-samples-master\endpoints\getting-started 目录中提供的 openapi-appengine.yaml 文件的内容:
- 在文本编辑器中打开
openapi-appengine.yaml,然后将内容替换为以下内容:openapi: 3.0.4 info: description: "A simple Google Cloud Endpoints API example." title: "Endpoints Example" version: "1.0.0" servers: - url: "https://YOUR_PROJECT_ID.appspot.com" 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: "Authenication info." content: "application/json": schema: $ref: "#/components/schemas/authInfoResponse" security: - google_jwt: [] "/auth/info/googleidtoken": get: description: "Returns the requests' authentication information." operationId: "authInfoGoogleIdToken" responses: "200": description: "Authenication info." content: "application/json": schema: $ref: "#/components/schemas/authInfoResponse" security: - google_id_token: [] components: schemas: echoMessage: type: "object" properties: message: type: "string" authInfoResponse: type: "object" properties: id: type: "string" email: type: "string" securitySchemes: # 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: 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" # This must match the "aud" field in the JWT. You can add multiple # audiences to accept JWTs from multiple clients. # 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: type: oauth2 flows: implicit: authorizationUrl: "" scopes: {} x-google-auth: issuer: "https://accounts.google.com" jwksUri: "https://www.googleapis.com/oauth2/v1/certs" audiences: - "YOUR_CLIENT_ID"
- 保存
openapi.yaml的新内容。
本教程使用特定于 Google 的 OpenAPI 规范扩展程序,该扩展程序可让您配置服务名称。指定服务名称的方法取决于您使用的 OpenAPI 规范版本。
OpenAPI 2.0
使用 host 字段指定服务名称:
host: YOUR_PROJECT_ID.appspot.com
要配置 Endpoints,请执行以下操作:
- 打开
openapi-appengine.yaml文件。 - 在
host字段中,将 YOUR_PROJECT_ID 替换为您的 Google Cloud 项目 ID。 - 保存
openapi-appengine.yaml文件。
OpenAPI 3.x
使用 servers 对象中的 url 字段指定服务名称:
servers: - url: https://YOUR_PROJECT_ID.appspot.com x-google-endpoint: {}
要配置 Endpoints,请执行以下操作:
- 打开
openapi-appengine.yaml文件。 - 如果您的
openapi-appengine.yaml文件包含host字段,请将其移除。 - 添加一个
servers对象,如下所示。 - 在
url字段中,将 YOUR_PROJECT_ID 替换为您的 Google Cloud 项目 ID。 - 保存
openapi-appengine.yaml文件。
部署 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 [example-project-12345.appspot.com]
在上面的示例中,2017-02-13r0 是服务配置 ID,example-project-12345.appspot.com 是 Endpoints 服务。服务配置 ID 由日期戳后跟一个修订版本号组成。如果您在同一天再次部署 openapi.yaml 文件,服务配置 ID 中的修订版本号将递增。您可以在 Google Cloud 控制台中的 Endpoints > 服务页面上查看 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 后端
到目前为止,您已将 OpenAPI 文档部署到 Service Management,但尚未部署为 API 后端提供服务的代码。本部分将逐步介绍如何将示例 API 和 ESP 部署到 App Engine。
如需部署 API 后端,请执行以下操作:
- 打开
endpoints/getting-started/src/IO.Swagger/app.yaml文件,并添加您的服务名称: - 保存
app.yaml文件。 - 确保您位于
endpoints/getting-started目录中,即您的openapi.yaml配置文件所在的目录中。 - 将示例 API 和 ESP 部署到 App Engine:
dotnet restore dotnet publish gcloud app deploy src\IO.Swagger\bin\Debug\netcoreapp2.0\publish\app.yamlgcloud app deploy命令会创建YOUR_PROJECT_ID.appspot.com格式的 DNS 记录,您在向 API 发送请求时会用到它。建议您等待几分钟,在 App Engine 完全初始化后向 API 发送请求。
将 ENDPOINTS-SERVICE-NAME 替换为 Endpoints 服务的名称。该名称与您在 OpenAPI 文档的 host 字段中配置的名称相同。例如:
endpoints_api_service: name: example-project-12345.appspot.com rollout_strategy: managed
rollout_strategy: managed 选项可将 ESP 配置为使用最新部署的服务配置。指定此选项后,在部署新的服务配置后,ESP 最多会在 5 分钟内检测到更改并自动开始使用该服务配置。建议您指定此选项,而非让 ESP 使用特定的配置 ID。
由于 endpoints_api_service 部分包含在 app.yaml 文件内,因此 gcloud app deploy 命令会将单独容器中的 ESP 部署到您的 App Engine 柔性环境中,并在该环境中对 ESP 进行配置。所有请求流量均通过 ESP 路由。ESP 会作为代理将请求和响应传输到运行后端服务器代码的容器,并从中提取请求和响应。
如果您收到错误消息,请参阅排查 App Engine 柔性部署问题。
如需了解详情,请参阅部署 API 后端。
向 API 发送请求
部署示例 API 后,您可以向其发送请求:
创建 API 密钥并设置环境变量
示例代码需要 API 密钥。为简化请求,请为 API 密钥设置环境变量。
在您用于 API 的同一 Google Cloud 项目中,在 API 凭据页面上创建 API 密钥。如果要在其他 Google Cloud 项目中创建 API 密钥,请参阅在 Google Cloud 项目中启用 API。
- 点击创建凭据,然后选择 API 密钥。
- 将密钥复制到剪贴板。
- 点击关闭。
- 在本地计算机上,粘贴 API 密钥以将其分配给环境变量:
$Env:ENDPOINTS_KEY="AIza..."
发送请求
在 PowerShell 中,为您的 App Engine 项目网址设置环境变量。将 YOUR_PROJECT_ID 替换为您的Google Cloud 项目 ID。
$Env:ENDPOINTS_HOST="https://YOUR_PROJECT_ID.appspot.com"使用之前设置的
ENDPOINTS_HOST和ENDPOINTS_KEY环境变量测试 HTTP 请求:Invoke-WebRequest "$ENDPOINTS_HOST/echo?key=$ENDPOINTS_KEY" ` -Body '{"message": "hello world"}' -Method POST ` -ContentType "application/json"
在上面的示例中,前两行以反引号结束。将示例粘贴到 PowerShell 中时,请确保反引号后面没有空格。 要了解示例请求中使用的选项,请参阅 Microsoft 文档中的 Invoke-WebRequest。
API 会回显您向其发送的消息,并以如下内容作为响应:
{
"message": "hello world"
}
如果未成功收到响应,请参阅排查响应错误。
您刚刚在 Endpoints 中部署并测试了一个 API!
跟踪 API 活动
在 Endpoints 页面中查看 API 的活动图表。
请求可能需要一些时间才能体现在图表中。
在“日志浏览器”页面中查看 API 的请求日志。
清理
为避免因本教程中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的项目,或者保留项目但删除各个资源。
清理
如需了解如何停止本教程使用的服务,请参阅删除 API 和 API 实例。