이 가이드에서는 App Engine 가변형 환경의 인스턴스에서 실행되는 샘플 .NET 코어 API와 Extensible Service Proxy(ESP)를 구성 및 배포하는 방법을 설명합니다. 샘플 API는 OpenAPI 사양을 사용하여 설명됩니다. 이 가이드에서는 API 키를 만들어 API에 대한 요청에 사용하는 방법도 설명합니다.
Cloud Endpoints 개요는 Endpoints 정보와 Endpoints 아키텍처를 참조하세요.
목표
아래의 개략적인 작업 목록을 사용하여 가이드를 진행합니다. API에 요청을 보내려면 모든 작업을 수행해야 합니다.
- Google Cloud 프로젝트를 설정하고, 필요한 소프트웨어를 설치하고, App Engine 애플리케이션을 만듭니다. 시작하기 전에를 참고하세요.
- 샘플 코드를 다운로드합니다. 샘플 코드 받기를 참조하세요.
- Endpoints를 구성하는 데 사용되는
openapi.yaml파일을 구성합니다. 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 중 하나를 사용하는 것이 좋습니다.
- macOS, Linux, Windows에서 실행되는 Visual Studio Code. Visual Studio Code를 사용하는 경우에는 .NET Core 2.x도 설치해야 합니다.
- .NET Core 2.x를 포함하는 Windows용 Visual Studio 2017. Visual Studio 2017을 사용하는 경우에는 IDE에 App Engine 배포를 통합하는 Visual Studio용 Google Tools 플러그인을 사용하는 것이 좋습니다.
- .NET Core 2.x를 포함하는 Mac용 Visual Studio.
애플리케이션이 요청을 샘플 API로 전송하도록 해야 합니다. 이 가이드에서 제공하는 예시에서는 PowerShell 3.0 이상에서 지원되는
Invoke-WebRequest를 사용합니다.- 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디렉터리의 파일을 수정합니다.
엔드포인트 구성
앱의 노출 영역과 인증 요구사항을 설명하는 OpenAPI 2.0 또는 OpenAPI 3.x 기반의 OpenAPI 문서가 있어야 합니다. 자세한 내용은 지원되는 OpenAPI 버전을 참고하세요.
ESPv2가 앱을 호출하는 데 필요한 정보를 갖도록 각 앱의 URL이 포함된 Google 전용 필드도 추가해야 합니다. 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"
호스트 필드가 있는 줄에서 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의 새 콘텐츠를 저장합니다.
이 튜토리얼에서는 서비스 이름을 구성할 수 있는 OpenAPI 사양에 대한 Google 관련 확장 프로그램을 사용합니다. 서비스 이름을 지정하는 방법은 사용 중인 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의 버전 번호가 증가합니다. Endpoints 서비스 구성은 Google Cloud 콘솔의 Endpoints > 서비스 페이지에서 확인할 수 있습니다.
오류 메시지가 나타나면 Endpoints 구성 배포 문제해결을 참조하세요.
필수 서비스 확인
Endpoints와 ESP를 사용하려면 최소한 다음 Google 서비스를 사용 설정해야 합니다.| 이름 | 제목 |
|---|---|
servicemanagement.googleapis.com |
Service Management API |
servicecontrol.googleapis.com |
Service Control API |
대부분의 경우 gcloud endpoints services deploy 명령어를 사용하여 이러한 필수 서비스를 사용 설정할 수 있습니다. 하지만 다음과 같은 경우에는 gcloud 명령어가 성공적으로 완료되더라도 필수 서비스가 사용 설정되지 않습니다.
Terraform과 같은 타사 애플리케이션을 사용하고 이러한 서비스를 포함하지 않은 경우
이러한 서비스가 명시적으로 사용 중지된 기존Google Cloud 프로젝트에 Endpoints 구성을 배포한 경우
다음 명령어를 사용하여 필수 서비스가 사용 설정되어 있는지 확인합니다.
gcloud services list
필수 서비스가 나열되지 않으면 서비스를 사용 설정하세요.
gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.comEndpoints 서비스도 사용 설정해야 합니다.
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 엔드포인트 구성의name필드에 지정한 항목입니다.
gcloud 명령어에 대한 자세한 내용은 gcloud 서비스를 참조하세요.
API 백엔드 배포
지금까지 OpenAPI 문서를 Service Management에 배포했지만 아직 API 백엔드를 제공할 코드를 배포하지 않았습니다. 이 섹션은 샘플 API와 ESP를 App Engine에 배포하는 방법을 설명합니다.
API 백엔드를 배포하려면 다음 안내를 따르세요.
endpoints/getting-started/src/IO.Swagger/app.yaml파일을 열고 서비스 이름을 추가합니다.app.yaml파일을 저장합니다.- 현재 위치가
openapi.yaml구성 파일이 있는endpoints/getting-started디렉터리인지 확인합니다. - 샘플 API와 ESP를 App Engine에 배포합니다.
dotnet restore dotnet publish gcloud app deploy src\IO.Swagger\bin\Debug\netcoreapp2.0\publish\app.yamlgcloud app deploy명령어는 API에 요청을 보낼 때 사용하는YOUR_PROJECT_ID.appspot.com형식의 DNS 레코드를 만듭니다. API에 요청을 보내기 전에 App Engine이 완전히 초기화될 때까지 몇 분 기다리는 것이 좋습니다.
ENDPOINTS-SERVICE-NAME은 Endpoints 서비스 이름으로 바꿉니다. 이 이름은 OpenAPI 문서의 host 필드에서 구성한 것과 동일한 이름입니다. 예를 들면 다음과 같습니다.
endpoints_api_service: name: example-project-12345.appspot.com rollout_strategy: managed
rollout_strategy: managed 옵션은 ESP가 배포된 최신 서비스 구성을 사용하도록 구성합니다. 이 옵션을 지정하면 새 서비스 구성을 배포하고 최대 5분 후 ESP가 변경사항을 감지하고 자동으로 사용하기 시작합니다. ESP에 사용할 특정 구성 ID 대신 이 옵션을 지정하는 것이 좋습니다.
app.yaml 파일에 endpoints_api_service 섹션이 포함되었기 때문에 gcloud app deploy 명령어는 App Engine 가변형 환경에 별도의 컨테이너로 ESP를 배포하고 구성합니다. 모든 요청 트래픽이 ESP를 통해 라우팅되며, ESP는 백엔드 서버 코드를 실행하는 컨테이너의 요청과 응답을 프록시합니다.
오류 메시지가 나타나면 App Engine 가변형 배포 문제해결을 참조하세요.
자세한 내용은 API 백엔드 배포를 참조하세요.
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 프로젝트 URL의 환경 변수를 설정합니다. 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 인스턴스 삭제를 참조하세요.