תחילת העבודה עם Cloud Endpoints בסביבה הגמישה של App Engine באמצעות ESP

במדריך הזה נסביר איך להגדיר ולפרוס API לדוגמה ואת Extensible Service Proxy‏ (ESP) שפועל במופע בסביבה הגמישה של App Engine. ממשק ה-API לדוגמה מתואר באמצעות מפרט OpenAPI. במדריך מוסבר גם איך ליצור מפתח API ולהשתמש בו בבקשות ל-API.

סקירה כללית של Cloud Endpoints זמינה במאמרים מידע על Endpoints וארכיטקטורת Endpoints.

מטרות

במהלך העבודה עם המדריך, תוכלו להשתמש ברשימת המשימות הכללית הבאה. כדי לשלוח בקשות ל-API, צריך לבצע את כל המשימות.

  1. מגדירים Google Cloud פרויקט, מתקינים את התוכנה הנדרשת ויוצרים אפליקציית App Engine. אפשר לעיין במאמר לפני שמתחילים.
  2. מורידים את הקוד לדוגמה. איך מקבלים את הקוד לדוגמה
  3. מגדירים את הקובץ openapi-appengine.yaml, שמשמש להגדרת נקודות קצה. איך מגדירים נקודות קצה
  4. פורסים את ההגדרה של Endpoints כדי ליצור שירות Endpoints. איך פורסים את ההגדרה של נקודות הקצה
  5. פורסים את ה-API ואת ESP ב-App Engine. מידע נוסף זמין במאמר בנושא פריסת קצה העורפי של ה-API.
  6. שליחת בקשה ל-API. שליחת בקשה ל-API
  7. מעקב אחר פעילות ב-API. מידע נוסף זמין במאמר בנושא מעקב אחר פעילות של API.
  8. כדי להימנע מחיובים בחשבון Google Cloud , מידע נוסף זמין בקטע הסרת המשאבים.

עלויות

במסמך הזה משתמשים ברכיבים הבאים של Google Cloud, והשימוש בהם כרוך בתשלום:

כדי להעריך את ההוצאות בהתאם לתחזית השימוש שלכם, אתם יכולים להיעזר במחשבון העלויות.

משתמשים חדשים של Google Cloud ? יכול להיות שאתם זכאים לתקופת ניסיון בחינם.

כשמסיימים את המשימות שמתוארות במסמך הזה אפשר למחוק את המשאבים שיצרתם כדי להימנע מחיובים נוספים. מידע נוסף זמין בקטע הסרת המשאבים.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  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. חשוב לרשום את מזהה הפרויקט כי תצטרכו אותו בהמשך.
  7. אתם צריכים אפליקציה כדי לשלוח בקשות ל-API לדוגמה.

    • משתמשי Linux ו-macOS: במדריך הזה יש דוגמה לשימוש ב-curl, שבדרך כלל מותקן מראש במערכת ההפעלה. אם אין לכם את curl, אתם יכולים להוריד אותו מcurl דף ההורדות והגרסאות.
    • משתמשי Windows: במדריך הזה יש דוגמה לשימוש ב-Invoke-WebRequest, שנתמך ב-PowerShell 3.0 ואילך.
  8. הורדה של Google Cloud CLI
  9. מעדכנים את ה-CLI של gcloud ומתקינים את רכיבי Endpoints.
    gcloud components update
  10. מוודאים ש-Google Cloud CLI ‏ (gcloud) מורשה לגשת לנתונים ולשירותים שלכם ב- Google Cloud:
    gcloud auth login
    בכרטיסייה החדשה בדפדפן שנפתחת, בוחרים חשבון.
  11. מגדירים את פרויקט ברירת המחדל למזהה הפרויקט.
    gcloud config set project YOUR_PROJECT_ID

    מחליפים את YOUR_PROJECT_ID במזהה הפרויקט. אם יש לכם פרויקטים אחרים Google Cloud ואתם רוצים להשתמש ב-gcloudכדי לנהל אותם, תוכלו לקרוא את המאמר בנושא ניהול ההגדרות האישיות של ה-CLI של gcloud.

  12. בוחרים את האזור שבו רוצים ליצור את אפליקציית App Engine. כדי לקבל רשימה של אזורים, מריצים את הפקודה הבאה:
    gcloud app regions list
  13. יוצרים אפליקציית App Engine. מחליפים את YOUR_PROJECT_ID במזהה הפרויקט ב- Google Cloudואת YOUR_REGION באזור שבו רוצים ליצור את האפליקציה ב-App Engine.
      gcloud app create \
      --project=YOUR_PROJECT_ID \
      --region=YOUR_REGION
    
  14. אם לחשבון השירות שמוגדר כברירת מחדל ב-App Engine אין את התפקיד 'עריכה' (roles/editor), צריך להעניק את ההרשאות הבאות:
    • מקצים את ההרשאה roles/servicemanagement.serviceConsumer לחשבון השירות של App Engine שמוגדר כברירת מחדל ברמת השירות.
    • מקצים את ההרשאה roles/servicemanagement.serviceController לחשבון השירות של App Engine שמוגדר כברירת מחדל ברמת הפרויקט.

    במאמר ניהול הגישה באמצעות מסוף Google Cloud מוסבר איך נותנים תפקידים לחשבון השירות.

קבלת הקוד לדוגמה

Java

כדי לשכפל או להוריד את ה-API לדוגמה:

  1. קוד לדוגמה שמשתמש ב-Maven. אם לא מותקנת אצלכם גרסה Maven 3.3.9 ומעלה, צריך להוריד ולהתקין אותה.
  2. משכפלים את מאגר האפליקציה לדוגמה ומעבירים אותו למכונה המקומית:
    git clone https://github.com/GoogleCloudPlatform/java-docs-samples

    אפשרות אחרת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

  3. עוברים לספרייה שמכילה את הקוד לדוגמה:
    cd java-docs-samples/endpoints/getting-started
Python

כדי לשכפל או להוריד את ה-API לדוגמה:

  1. משכפלים את מאגר האפליקציה לדוגמה ומעבירים אותו למכונה המקומית:
    git clone https://github.com/GoogleCloudPlatform/python-docs-samples

    אפשרות אחרת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

  2. עוברים לספרייה שמכילה את הקוד לדוגמה:
    cd python-docs-samples/endpoints/getting-started
Go

כדי לשכפל או להוריד את ה-API לדוגמה:

  1. מוודאים שמשתנה הסביבה GOPATH מוגדר.
  2. משכפלים את מאגר האפליקציה לדוגמה ומעבירים אותו למכונה המקומית:
    go get -d github.com/GoogleCloudPlatform/golang-samples/endpoints/getting-started
  3. עוברים לספרייה שמכילה את הקוד לדוגמה:
    cd $GOPATH/src/github.com/GoogleCloudPlatform/golang-samples/endpoints/getting-started
PHP

כדי לשכפל או להוריד את ה-API לדוגמה:

  1. משכפלים את מאגר האפליקציה לדוגמה ומעבירים אותו למכונה המקומית:
    git clone https://github.com/GoogleCloudPlatform/php-docs-samples

    אפשרות אחרת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

  2. עוברים לספרייה שמכילה את הקוד לדוגמה:
    cd php-docs-samples/endpoints/getting-started
Ruby

כדי לשכפל או להוריד את ה-API לדוגמה:

  1. משכפלים את מאגר האפליקציה לדוגמה ומעבירים אותו למכונה המקומית:
    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples

    אפשרות אחרת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

  2. עוברים לספרייה שמכילה את הקוד לדוגמה:
    cd ruby-docs-samples/endpoints/getting-started
NodeJS

כדי לשכפל או להוריד את ה-API לדוגמה:

  1. משכפלים את מאגר האפליקציה לדוגמה ומעבירים אותו למכונה המקומית:
    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples

    אפשרות אחרת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

  2. עוברים לספרייה שמכילה את הקוד לדוגמה:
    cd nodejs-docs-samples/endpoints/getting-started

הגדרת נקודות קצה

צריך ליצור מסמך OpenAPI שמבוסס על OpenAPI 2.0 או על OpenAPI 3.x, ומתאר את הסביבה של האפליקציות ואת דרישות האימות. מידע נוסף זמין במאמר גרסאות נתמכות של OpenAPI.

צריך גם להוסיף שדה ספציפי ל-Google שמכיל את כתובת ה-URL של כל אפליקציה, כדי של-ESPv2 יהיה המידע שהוא צריך כדי להפעיל אפליקציה. אם אתם חדשים ב-OpenAPI, תוכלו לקרוא מידע נוסף בסקירה כללית של OpenAPI.

OpenAPI 2.0

כדי להגדיר נקודות קצה באמצעות מפרט OpenAPI 2.0, אפשר להשתמש בקובץ openapi-appengine.yaml שזמין בספרייה dotnet-docs-samples-master\endpoints\getting-started של קוד הדוגמה שהורדתם.

התוכן של מפרט 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 .

‫OpenAPI 3.x

כדי להגדיר את Endpoints באמצעות מפרט OpenAPI 3.x, אפשר להחליף את התוכן של הקובץ openapi-appengine.yaml שזמין בספרייה dotnet-docs-samples-master\endpoints\getting-started של קוד הדוגמה שהורדתם:

  1. פותחים את הקובץ 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"
            # This must match the "aud" field in the JWT. You can add multiple
            # audiences to accept JWTs from multiple clients.
            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:
          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. שומרים את התוכן החדש של openapi.yaml.

במדריך הזה נעשה שימוש בתוסף ספציפי ל-Google למפרט OpenAPI, שמאפשר להגדיר את שם השירות. השיטה לציון שם השירות תלויה בגרסה של מפרט OpenAPI שבה אתם משתמשים.

OpenAPI 2.0

משתמשים בשדה host כדי לציין את שם השירות:

host: YOUR_PROJECT_ID.appspot.com

כדי להגדיר נקודות קצה:

  1. פותחים את הקובץ openapi-appengine.yaml.
  2. בשדה host, מחליפים את YOUR_PROJECT_ID במזהה הפרויקט ב- Google Cloud .
  3. שומרים את קובץ ה-openapi-appengine.yaml.

‫OpenAPI 3.x

משתמשים בשדה url באובייקט servers כדי לציין את שם השירות:

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

כדי להגדיר נקודות קצה:

  1. פותחים את הקובץ openapi-appengine.yaml.
  2. אם בקובץ openapi-appengine.yaml יש שדה host, צריך להסיר אותו.
  3. מוסיפים אובייקט servers כמו שמוצג.
  4. בשדה url, מחליפים את YOUR_PROJECT_ID במזהה הפרויקט ב- Google Cloud .
  5. שומרים את קובץ ה-openapi-appengine.yaml.

פריסת ההגדרה של נקודות הקצה

כדי לפרוס את ההגדרה של Endpoints, משתמשים בפקודה gcloud endpoints services deploy. הפקודה הזו משתמשת ב-Service Management כדי ליצור שירות מנוהל.

כדי לפרוס את ההגדרה של Endpoints:

  1. מוודאים שאתם נמצאים בספרייה שבה נמצא קובץ ההגדרות openapi.yaml.
  2. מעלים את ההגדרה ויוצרים שירות מנוהל:
    gcloud endpoints services deploy openapi.yaml
    

הפקודה gcloud קוראת ל-Service Management API כדי ליצור שירות מנוהל עם השם שציינתם בשדה host או servers.url בקובץ openapi.yaml. שירות ניהול השירותים מגדיר את השירות בהתאם להגדרות בקובץ openapi.yaml. כשמבצעים שינויים ב-openapi.yaml, צריך לפרוס מחדש את הקובץ כדי לעדכן את שירות נקודות הקצה.

במהלך היצירה וההגדרה של השירות, Service Management מציג מידע במסוף. אפשר להתעלם בבטחה מהאזהרות לגבי הנתיבים בקובץ openapi.yaml שלא דורשים מפתח API. בסיום הגדרת השירות, Service Management מציג הודעה עם מזהה הגדרת השירות ושם השירות, בדומה להודעה הבאה:

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

בדוגמה שלמעלה, 2017-02-13r0 הוא מזהה הגדרת השירות ו-example-project-12345.appspot.com הוא שירות ה-Endpoints. מזהה הגדרות השירות מורכב מחותמת תאריך וממספר גרסה. אם תפעילו את הקובץ openapi.yaml שוב באותו יום, מספר הגרסה יוגדל במזהה תצורת השירות. אפשר לראות את הגדרת השירות של Endpoints בדף Endpoints > Services במסוף Google Cloud .

אם מופיעה הודעת שגיאה, אפשר לעיין במאמר בנושא פתרון בעיות בהטמעה של הגדרות Endpoints.

בדיקת השירותים הנדרשים

לפחות, צריך להפעיל את שירותי Google הבאים כדי להשתמש ב-Endpoints וב-ESP:
שם כותרת
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, נכנסים לדף Endpoints במסוף Cloud. רשימת האפשרויות האפשריות של ENDPOINTS_SERVICE_NAME מוצגת בעמודה שם השירות.

  • ב-OpenAPI, ‏ ENDPOINTS_SERVICE_NAME הוא הערך שציינתם בשדה host במפרט OpenAPI. ב-gRPC, ‏ ENDPOINTS_SERVICE_NAME הוא הערך שציינתם בשדה name בהגדרות של נקודות הקצה של gRPC.

מידע נוסף על פקודות gcloud זמין במאמר שירותי gcloud.

פריסת ה-API backend

עד עכשיו פרסתם את מסמך ה-OpenAPI ב-Service Management, אבל עדיין לא פרסתם את הקוד שמפעיל את ה-backend של ה-API. בקטע הזה מוסבר איך פורסים את ה-API ואת ה-ESP לדוגמה ב-App Engine.

כדי לפרוס את העורף של ה-API:

  1. מוסיפים את שם השירות לקובץ app.yaml:

    Java

    פותחים את הקובץ endpoints/getting-started/src/main/appengine/app.yaml.

    endpoints_api_service:
      # The following values are to be replaced by information from the output of
      # 'gcloud endpoints services deploy openapi-appengine.yaml' command.
      name: ENDPOINTS-SERVICE-NAME
      rollout_strategy: managed

    Python

    פותחים את הקובץ endpoints/getting-started/app.yaml.

    endpoints_api_service:
      # The following values are to be replaced by information from the output of
      # 'gcloud endpoints services deploy openapi-appengine.yaml' command.
      name: ENDPOINTS-SERVICE-NAME
      rollout_strategy: managed

    Go

    פותחים את הקובץ endpoints/getting-started/app.yaml.

    endpoints_api_service:
      # The following values are to be replaced by information from the output of
      # 'gcloud endpoints services deploy openapi-appengine.yaml' command.
      name: ENDPOINTS-SERVICE-NAME
      rollout_strategy: managed

    PHP

    פותחים את הקובץ endpoints/getting-started/app.yaml.

    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=YOUR-PROJECT-ID.appspot.com
      #
      name: ENDPOINTS-SERVICE-NAME
      rollout_strategy: managed

    Ruby

    פותחים את הקובץ endpoints/getting-started/app.yaml.

    endpoints_api_service:
      # The following values are to be replaced by information from the output of
      # 'gcloud endpoints services deploy openapi-appengine.yaml' command.
      name: ENDPOINTS-SERVICE-NAME
      rollout_strategy: managed

    NodeJS

    פותחים את הקובץ endpoints/getting-started/app.yaml.

    endpoints_api_service:
      # The following values are to be replaced by information from the output of
      # 'gcloud endpoints services deploy openapi-appengine.yaml' command.
      name: ENDPOINTS-SERVICE-NAME
      rollout_strategy: managed

    מחליפים את ENDPOINTS-SERVICE-NAME בשם של שירות Endpoints. זהו אותו שם שהגדרתם בשדה host במסמך OpenAPI. לדוגמה:

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

    האפשרות rollout_strategy: managed מגדירה את ESP כך שישתמש בהגדרת השירות העדכנית ביותר שנפרסה. אם תבחרו באפשרות הזו, עד 5 דקות אחרי שתפרסו הגדרת שירות חדשה, ESP יזהה את השינוי ויתחיל להשתמש בה באופן אוטומטי. אנחנו ממליצים לציין את האפשרות הזו במקום מזהה תצורה ספציפי לשימוש ב-ESP.

  2. שומרים את קובץ ה-app.yaml.
  3. מכיוון שהקטע endpoints_api_service כלול בקובץ app.yaml, הפקודה gcloud app deploy פורסת ומגדירה את ESP במאגר נפרד מסביבת App Engine הגמישה. כל תעבורת הבקשות מנותבת דרך ESP, והוא משמש כפרוקסי לבקשות ולתגובות אל הקונטיינר שבו פועל קוד שרת הקצה העורפי וממנו.

  4. מוודאים שאתם נמצאים בספרייה שבה נמצא קובץ ההגדרות openapi.yaml.
  5. מריצים את הפקודה הבאה כדי לפרוס את ה-API לדוגמה ואת ESP ב-App Engine:
  6. Java

    פריסה באמצעות Maven:

    mvn appengine:stage
    gcloud app deploy target/appengine-staging
    
    Python
    gcloud app deploy
    קדימה
    gcloud app deploy
    PHP
    gcloud app deploy
    Ruby
    gcloud app deploy
    NodeJS
    gcloud app deploy

    הפקודה gcloud app deploy יוצרת רשומת DNS בפורמט YOUR_PROJECT_ID.appspot.com, שבה משתמשים כששולחים בקשות ל-API. מומלץ להמתין כמה דקות לפני שליחת בקשות ל-API בזמן שהאפליקציה עוברת אתחול מלא ב-App Engine.

אם מופיעה הודעת שגיאה, אפשר להיעזר במאמר פתרון בעיות בפריסה של App Engine Flexible.

מידע נוסף מופיע במאמר פריסת קצה העורפי של ה-API.

שליחת בקשות ל-API

עכשיו, כשהשירות פועל ב-App Engine, אפשר לשלוח אליו בקשות.

יצירת מפתח API והגדרת משתנה סביבה

קוד לדוגמה דורש מפתח API. כדי לפשט את הבקשה, מגדירים משתנה סביבתי למפתח ה-API.

  1. באותו פרויקט שבו השתמשתם עבור ה-API, יוצרים מפתח API בדף 'פרטי כניסה ל-API'. Google Cloud אם רוצים ליצור מפתח API בפרויקט אחר ב- Google Cloud , אפשר לעיין במאמר בנושא הפעלת API בפרויקט Google Cloud .

    לדף Credentials

  2. לוחצים על Create credentials ואז על API key.
  3. מעתיקים את המפתח ללוח.
  4. לוחצים על Close.
  5. במחשב המקומי, מדביקים את מפתח ה-API כדי להקצות אותו למשתנה סביבה:
    • ב-Linux או ב-macOS: export ENDPOINTS_KEY=AIza...
    • ב-Windows PowerShell: ‏ $Env:ENDPOINTS_KEY="AIza..."

שליחת הבקשה

‫Linux או Mac OS

  1. יוצרים משתנה סביבה לכתובת ה-URL של פרויקט App Engine. מחליפים את YOUR_PROJECT_ID במזהה הפרויקט ב-Google Cloud :

    export ENDPOINTS_HOST=https://YOUR_PROJECT_ID.appspot.com

  2. שולחים בקשת HTTP באמצעות משתני הסביבה ENDPOINTS_HOST ו-ENDPOINTS_KEY שהגדרתם קודם:

    curl --request POST \
      --header "content-type:application/json" \
      --data '{"message":"hello world"}' \
      "${ENDPOINTS_HOST}/echo?key=${ENDPOINTS_KEY}"

במהלך curl הקודמים:

  • האפשרות --data מציינת את הנתונים שיישלחו ל-API.
  • האפשרות --header מציינת שהנתונים הם בפורמט JSON.

PowerShell

  1. יוצרים משתנה סביבה לכתובת ה-URL של פרויקט App Engine. מחליפים את YOUR_PROJECT_ID במזהה הפרויקט ב-Google Cloud :

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

  2. שולחים בקשת HTTP באמצעות משתני הסביבה ENDPOINTS_HOST ו-ENDPOINTS_KEY שהגדרתם קודם:

    (Invoke-WebRequest -Method POST -Body '{"message": "hello world"}' `
        -Headers @{"content-type"="application/json"} `
        -URI "$Env:ENDPOINTS_HOST/echo?key=$Env:ENDPOINTS_KEY").Content
    

בדוגמה הקודמת, שתי השורות הראשונות מסתיימות בגרש הפוך. כשמדביקים את הדוגמה ב-PowerShell, צריך לוודא שאין רווח אחרי התווים '`'. מידע על האפשרויות שבהן נעשה שימוש בבקשת הדוגמה מופיע במאמר Invoke-WebRequest במסמכי התיעוד של מיקרוסופט.

אפליקציה של צד שלישי

אפשר להשתמש באפליקציה של צד שלישי, כמו התוסף Postman לדפדפן Chrome, כדי לשלוח את הבקשה:

  • בוחרים באפשרות POST כפועל ה-HTTP.
  • בכותרת, בוחרים את המפתח content-type ואת הערך application/json.
  • בגוף ההודעה, מזינים את הפרטים הבאים:
    {"message":"hello world"}
  • בכתובת ה-URL, משתמשים בכתובת appspot.com ובמפתח ה-API בפועל ולא במשתני הסביבה. לדוגמה:
    https://example-project-12345.appspot.com/echo?key=AIza...

ה-API מחזיר את ההודעה ששלחתם לו, ומגיב עם:

{
  "message": "hello world"
}

אם לא קיבלתם תגובה, אפשר להיעזר במאמר בנושא פתרון בעיות שקשורות לתגובות.

הרגע פרסתם ובדקתם API ב-Endpoints!

מעקב אחר פעילות ב-API

  1. אפשר לראות את הגרפים של הפעילות ב-API בדף Endpoints (נקודות קצה).

    לדף Endpoints Services

    יכול להיות שיחלפו כמה רגעים עד שהבקשה תשתקף בתרשימים.

  2. מעיינים ביומני הבקשות של ה-API בדף Logs Explorer.

    כניסה לדף Logs Explorer

הסרת המשאבים

כדי להימנע מחיובים בחשבון Google Cloud בגלל השימוש במשאבים שנעשה במסגרת המדריך הזה, אפשר למחוק את הפרויקט שמכיל את המשאבים, או להשאיר את הפרויקט ולמחוק את המשאבים בנפרד.

במאמר מחיקת API ומופעי API מוסבר איך להפסיק את השירותים שבהם נעשה שימוש במדריך הזה.

המאמרים הבאים