Memulai Cloud Endpoints di lingkungan fleksibel App Engine (.NET) dengan ESP

Tutorial ini menunjukkan cara mengonfigurasi dan men-deploy contoh API .NET Core dan Extensible Service Proxy (ESP) yang berjalan di instance dalam lingkungan fleksibel App Engine. Contoh API dijelaskan menggunakan spesifikasi OpenAPI. Tutorial ini juga menunjukkan cara membuat kunci API dan menggunakannya dalam permintaan ke API.

Untuk ringkasan Cloud Endpoints, lihat Tentang Endpoints dan Arsitektur Endpoints.

Tujuan

Gunakan daftar tugas tingkat tinggi berikut saat Anda mengerjakan tutorial ini. Semua tugas diperlukan agar berhasil mengirim permintaan ke API.

  1. Siapkan Google Cloud project, instal software yang diperlukan, dan buat aplikasi App Engine. Lihat Sebelum memulai.
  2. Download kode contoh. Lihat Mendapatkan kode contoh.
  3. Konfigurasi file openapi.yaml, yang digunakan untuk mengonfigurasi Endpoints. Lihat Mengonfigurasi Endpoint.
  4. Deploy konfigurasi Endpoints untuk membuat layanan Endpoints. Lihat Men-deploy konfigurasi Endpoints.
  5. Deploy API contoh dan ESP ke App Engine. Lihat Men-deploy backend API.
  6. Kirim permintaan ke API. Lihat Mengirim permintaan ke API.
  7. Lacak aktivitas API. Lihat Melacak aktivitas API.
  8. Hindari menimbulkan biaya pada akun Google Cloud Anda. Lihat Pembersihan.

Biaya

Di dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga.

Pengguna Google Cloud baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Setelah menyelesaikan tugas yang dijelaskan dalam dokumen ini, Anda dapat menghindari penagihan berkelanjutan dengan menghapus resource yang Anda buat. Untuk mengetahui informasi selengkapnya, baca bagian Pembersihan.

Sebelum memulai

Sebelum memulai

  1. 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.
  2. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Verify that billing is enabled for your Google Cloud project.

  6. Catat project ID karena akan diperlukan nanti.
  7. Tutorial ini memerlukan .NET Core 2.x SDK, yang dapat Anda gunakan dengan editor teks apa pun. Meskipun lingkungan pengembangan terintegrasi (IDE) tidak diperlukan, untuk memudahkan, sebaiknya Anda menggunakan salah satu IDE berikut:
  8. Anda memerlukan aplikasi untuk mengirim permintaan ke contoh API. Tutorial ini memberikan contoh penggunaan Invoke-WebRequest, yang didukung di PowerShell 3.0 dan yang lebih baru.

  9. Download Google Cloud CLI.
  10. Update gcloud CLI dan instal komponen Endpoints.
    gcloud components update
  11. Pastikan Google Cloud CLI (gcloud) diizinkan untuk mengakses data dan layanan Anda di Google Cloud:
    gcloud auth login
    Di tab browser baru yang terbuka, pilih akun.
  12. Tetapkan project default ke project ID Anda.
    gcloud config set project YOUR_PROJECT_ID

    Ganti YOUR_PROJECT_ID dengan project ID Google Cloud Anda. Jika Anda memiliki project Google Cloud lain, dan ingin menggunakan gcloud untuk mengelolanya, lihat Mengelola konfigurasi gcloud CLI.

  13. Pilih region tempat Anda ingin membuat aplikasi App Engine. Jalankan perintah berikut untuk mendapatkan daftar region:
    gcloud app regions list
  14. Buat aplikasi App Engine. Ganti YOUR_PROJECT_ID dengan Google Cloud project ID Anda dan YOUR_REGION dengan region tempat Anda ingin membuat aplikasi App Engine.
      gcloud app create \
      --project=YOUR_PROJECT_ID \
      --region=YOUR_REGION
    

Mendapatkan kode contoh

Untuk mendownload contoh API:

  1. Download kode contoh sebagai file ZIP.

  2. Ekstrak file ZIP dan ubah ke direktori dotnet-docs-samples-master\endpoints\getting-started.

  3. Buka GettingStarted.sln dengan Visual Studio, atau gunakan editor favorit Anda untuk mengedit file di direktori endpoints\getting-started\src\IO.Swagger.

Mengonfigurasi Endpoint

Anda harus memiliki dokumen OpenAPI berdasarkan OpenAPI 2.0 atau OpenAPI 3.x yang mendeskripsikan platform aplikasi Anda dan persyaratan autentikasi apa pun. Untuk mempelajari lebih lanjut, lihat Versi OpenAPI yang didukung.

Anda juga perlu menambahkan kolom khusus Google yang berisi URL untuk setiap aplikasi agar ESPv2 memiliki informasi yang diperlukan untuk memanggil aplikasi. Jika Anda baru menggunakan OpenAPI, lihat Ringkasan OpenAPI untuk mengetahui informasi selengkapnya.

OpenAPI 2.0

Untuk mengonfigurasi Endpoints menggunakan spesifikasi OpenAPI 2.0, Anda dapat menggunakan file openapi-appengine.yaml yang tersedia di direktori dotnet-docs-samples-master\endpoints\getting-started dari contoh kode yang didownload.

Isi spesifikasi OpenAPI 2.0 akan terlihat seperti berikut:

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"

Di baris dengan kolom host, ganti YOUR_PROJECT_ID dengan project ID Google Cloud Anda.

OpenAPI 3.x

Untuk mengonfigurasi Endpoints menggunakan spesifikasi OpenAPI 3.x, Anda dapat mengganti isi file openapi-appengine.yaml yang tersedia di direktori dotnet-docs-samples-master\endpoints\getting-started dari kode contoh yang didownload:

  1. Buka openapi-appengine.yaml di editor teks Anda dan ganti kontennya dengan berikut:
    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"
  2. Simpan konten baru openapi.yaml.

Tutorial ini menggunakan ekstensi khusus Google untuk spesifikasi OpenAPI yang memungkinkan Anda mengonfigurasi nama layanan. Metode untuk menentukan nama layanan bergantung pada versi spesifikasi OpenAPI yang Anda gunakan.

OpenAPI 2.0

Gunakan kolom host untuk menentukan nama layanan:

host: YOUR_PROJECT_ID.appspot.com

Untuk mengonfigurasi Endpoint:

  1. Buka file openapi-appengine.yaml.
  2. Di kolom host, ganti YOUR_PROJECT_ID dengan project ID Google Cloud Anda.
  3. Simpan file openapi-appengine.yaml.

OpenAPI 3.x

Gunakan kolom url dalam objek servers untuk menentukan nama layanan:

servers:
- url: https://YOUR_PROJECT_ID.appspot.com
  x-google-endpoint: {}

Untuk mengonfigurasi Endpoint:

  1. Buka file openapi-appengine.yaml.
  2. Jika file openapi-appengine.yaml Anda memiliki kolom host, hapus kolom tersebut.
  3. Tambahkan objek servers seperti yang ditunjukkan.
  4. Di kolom url, ganti YOUR_PROJECT_ID dengan project ID Google Cloud Anda.
  5. Simpan file openapi-appengine.yaml.

Men-deploy konfigurasi Endpoint

Untuk men-deploy konfigurasi Endpoints, Anda menggunakan perintah gcloud endpoints services deploy. Perintah ini menggunakan Service Management untuk membuat layanan terkelola.

Untuk men-deploy konfigurasi Endpoints:

  1. Pastikan Anda berada di direktori tempat file konfigurasi openapi.yaml Anda berada.
  2. Upload konfigurasi dan buat layanan terkelola:
    gcloud endpoints services deploy openapi.yaml
    

Kemudian, perintah gcloud memanggil Service Management API untuk membuat layanan terkelola dengan nama yang Anda tentukan di kolom host atau servers.url file openapi.yaml. Service Management mengonfigurasi layanan sesuai dengan setelan dalam file openapi.yaml. Saat membuat perubahan pada openapi.yaml, Anda harus men-deploy ulang file untuk memperbarui layanan Endpoints.

Saat membuat dan mengonfigurasi layanan, Pengelolaan Layanan menampilkan informasi ke terminal. Anda dapat mengabaikan peringatan tentang jalur dalam file openapi.yaml yang tidak memerlukan kunci API dengan aman. Setelah selesai mengonfigurasi layanan, Service Management akan menampilkan pesan dengan ID konfigurasi layanan dan nama layanan, yang mirip dengan berikut ini:

Service Configuration [2017-02-13r0] uploaded for service [example-project-12345.appspot.com]

Dalam contoh sebelumnya, 2017-02-13r0 adalah ID konfigurasi layanan, dan example-project-12345.appspot.com adalah layanan Endpoints. ID konfigurasi layanan terdiri dari stempel tanggal yang diikuti dengan nomor revisi. Jika Anda men-deploy file openapi.yaml lagi pada hari yang sama, nomor revisi akan bertambah dalam ID konfigurasi layanan. Anda dapat melihat konfigurasi layanan Endpoints di halaman Endpoints > Services di konsol Google Cloud .

Jika Anda menerima pesan error, lihat Memecahkan masalah deployment konfigurasi Endpoint.

Memeriksa layanan yang diperlukan

Minimal, Endpoints dan ESP memerlukan layanan Google berikut diaktifkan:
Nama Judul
servicemanagement.googleapis.com Service Management API
servicecontrol.googleapis.com Service Control API

Dalam sebagian besar kasus, perintah gcloud endpoints services deploy mengaktifkan layanan yang diperlukan ini. Namun, perintah gcloud berhasil diselesaikan, tetapi tidak mengaktifkan layanan yang diperlukan dalam situasi berikut:

  • Jika Anda menggunakan aplikasi pihak ketiga seperti Terraform, dan Anda tidak menyertakan layanan ini.

  • Anda men-deploy konfigurasi Endpoints ke projectGoogle Cloud yang sudah ada dan layanan ini dinonaktifkan secara eksplisit di project tersebut.

Gunakan perintah berikut untuk mengonfirmasi bahwa layanan yang diperlukan sudah diaktifkan:

gcloud services list

Jika Anda tidak melihat layanan yang diperlukan tercantum, aktifkan layanan tersebut:

gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.com

Aktifkan juga layanan Endpoints Anda:

gcloud services enable ENDPOINTS_SERVICE_NAME

Untuk menentukan ENDPOINTS_SERVICE_NAME, Anda dapat:

  • Setelah men-deploy konfigurasi Endpoints, buka halaman Endpoints di Konsol Cloud. Daftar ENDPOINTS_SERVICE_NAME yang mungkin ditampilkan di kolom Nama layanan.

  • Untuk OpenAPI, ENDPOINTS_SERVICE_NAME adalah yang Anda tentukan di kolom host spesifikasi OpenAPI. Untuk gRPC, ENDPOINTS_SERVICE_NAME adalah yang Anda tentukan di kolom name konfigurasi gRPC Endpoints.

Untuk mengetahui informasi selengkapnya tentang perintah gcloud, lihat layanan gcloud.

Men-deploy backend API

Sejauh ini Anda telah men-deploy dokumen OpenAPI ke Service Management, tetapi Anda belum men-deploy kode yang melayani backend API. Bagian ini memandu Anda men-deploy ESP dan contoh API ke App Engine.

Untuk men-deploy backend API:

  1. Buka file endpoints/getting-started/src/IO.Swagger/app.yaml, lalu tambahkan nama layanan Anda:
  2. endpoints_api_service:
      # The following values are to be replaced by information from the output of
      # 'gcloud endpoints services deploy openapi-appengine.yaml' command. If you have
      # previously run the deploy command, you can list your existing configuration
      # ids using the 'configs list' command as follows:
      # 'gcloud endpoints configs list --service=[PROJECT-ID].appspot.com'
      # where [PROJECT-ID].appspot.com is your Endpoints service name.
      name: ENDPOINTS-SERVICE-NAME
      rollout_strategy: managed
    

    Ganti ENDPOINTS-SERVICE-NAME dengan nama layanan Endpoints Anda. Nama ini sama dengan nama yang Anda konfigurasi di kolom host pada dokumen OpenAPI Anda. Contoh:

    endpoints_api_service:
      name: example-project-12345.appspot.com
      rollout_strategy: managed

    Opsi rollout_strategy: managed mengonfigurasi ESP untuk menggunakan konfigurasi layanan terbaru yang di-deploy. Saat Anda menentukan opsi ini, hingga 5 menit setelah Anda men-deploy konfigurasi layanan baru, ESP akan mendeteksi perubahan dan otomatis mulai menggunakannya. Sebaiknya tentukan opsi ini, bukan ID konfigurasi tertentu yang akan digunakan ESP.

  3. Simpan file app.yaml.
  4. Karena bagian endpoints_api_service disertakan dalam file app.yaml, perintah gcloud app deploy men-deploy dan mengonfigurasi ESP dalam penampung terpisah ke lingkungan fleksibel App Engine Anda. Semua traffic permintaan dirutekan melalui ESP, dan ESP membuat proxy permintaan dan respons ke dan dari penampung yang menjalankan kode server backend Anda.

  5. Pastikan Anda berada di direktori endpoints/getting-started, tempat file konfigurasi openapi.yaml Anda berada.
  6. Deploy contoh API dan ESP ke App Engine:

      dotnet restore
        dotnet publish
        gcloud app deploy src\IO.Swagger\bin\Debug\netcoreapp2.0\publish\app.yaml
    

    Perintah gcloud app deploy membuat data DNS dalam format YOUR_PROJECT_ID.appspot.com, yang Anda gunakan saat mengirim permintaan ke API. Sebaiknya tunggu beberapa menit sebelum mengirim permintaan ke API Anda saat App Engine diinisialisasi sepenuhnya.

Jika Anda menerima pesan error, lihat Memecahkan masalah deployment fleksibel App Engine.

Untuk mengetahui informasi selengkapnya, lihat Men-deploy Backend API.

Mengirim permintaan ke API

Setelah men-deploy contoh API, Anda dapat mengirim permintaan ke API tersebut.

Membuat kunci API dan menetapkan variabel lingkungan

Contoh kode memerlukan kunci API. Untuk menyederhanakan permintaan, Anda menetapkan variabel lingkungan untuk kunci API.

  1. Di project Google Cloud yang sama dengan yang Anda gunakan untuk API, buat kunci API di halaman kredensial API. Jika Anda ingin membuat kunci API di Google Cloud project lain, lihat Mengaktifkan API di Google Cloud project Anda.

    Buka halaman Kredensial

  2. Klik Create credentials, lalu pilih API key.
  3. Salin kunci ke papan klip.
  4. Klik Close.
  5. Di komputer lokal Anda, tempelkan kunci API untuk menetapkannya ke variabel lingkungan: $Env:ENDPOINTS_KEY="AIza..."

Kirim permintaan

  1. Di PowerShell, tetapkan variabel lingkungan untuk URL project App Engine Anda. Ganti YOUR_PROJECT_ID dengan Google Cloud project ID Anda.

    $Env:ENDPOINTS_HOST="https://YOUR_PROJECT_ID.appspot.com"

  2. Uji permintaan HTTP menggunakan variabel lingkungan ENDPOINTS_HOST dan ENDPOINTS_KEY yang Anda tetapkan sebelumnya:

    Invoke-WebRequest "$ENDPOINTS_HOST/echo?key=$ENDPOINTS_KEY" `
      -Body '{"message": "hello world"}' -Method POST `
      -ContentType "application/json"
    

Pada contoh sebelumnya, dua baris pertama diakhiri dengan tanda petik terbalik. Saat menempelkan contoh ke PowerShell, pastikan tidak ada spasi setelah tanda petik terbalik. Untuk mengetahui informasi tentang opsi yang digunakan dalam contoh permintaan, lihat Invoke-WebRequest dalam dokumentasi Microsoft.

API akan mengembalikan pesan yang Anda kirimkan, dan merespons dengan berikut ini:

{
  "message": "hello world"
}

Jika Anda tidak mendapatkan respons yang berhasil, lihat Memecahkan masalah error respons.

Anda baru saja men-deploy dan menguji API di Endpoints.

Melacak aktivitas API

  1. Lihat grafik aktivitas untuk API Anda di halaman Endpoints.

    Buka halaman Endpoints Services

    Mungkin perlu waktu beberapa saat agar permintaan ditampilkan dalam grafik.

  2. Lihat log permintaan untuk API Anda di halaman Logs Explorer.

    Buka halaman Logs Explorer

Pembersihan

Agar tidak perlu membayar biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, hapus project yang berisi resource tersebut, atau simpan project dan hapus setiap resource.

Pembersihan

Lihat Menghapus API dan instance API untuk mengetahui informasi tentang cara menghentikan layanan yang digunakan oleh tutorial ini.

Langkah berikutnya