HTTP のチュートリアル


このシンプルなチュートリアルでは、Cloud Run functions の HTTP 関数の作成、デプロイ、トリガーを行う方法について説明します。

目標

費用

このドキュメントでは、課金対象である次の Google Cloudコンポーネントを使用します。

  • Cloud Run functions

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。

新規の Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

始める前に

  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.

    Go to project selector

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

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  7. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  10. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  13. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  14. gcloud CLI がすでにインストールされている場合は、次のコマンドを実行して更新します。

    gcloud components update
  15. 開発環境を準備します。
  16. アプリケーションの準備

    1. ローカルマシンにサンプルアプリのリポジトリのクローンを作成します。

      Node.js

      git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

      または、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

      Python

      git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

      または、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

      Go

      git clone https://github.com/GoogleCloudPlatform/golang-samples.git

      または、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

      Java

      git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

      または、zip 形式のサンプルをダウンロードし、ファイルを抽出してもかまいません。

      Ruby

      git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

      または、zip 形式のサンプルをダウンロードしてファイルを抽出してもかまいません。

    2. Cloud Run functions のサンプルコードが含まれているディレクトリに移動します。

      Node.js

      cd nodejs-docs-samples/functions/helloworld/

      Python

      cd python-docs-samples/functions/helloworld/

      Go

      cd golang-samples/functions/helloworld/

      Java

      cd java-docs-samples/functions/helloworld/helloworld/

      Ruby

      cd ruby-docs-samples/functions/helloworld/

    3. サンプルコードを見てみましょう。

      Node.js

      const functions = require('@google-cloud/functions-framework');
      
      // Register an HTTP function with the Functions Framework that will be executed
      // when you make an HTTP request to the deployed function's endpoint.
      functions.http('helloGET', (req, res) => {
        res.send('Hello World!');
      });

      Python

      import functions_framework
      
      @functions_framework.http
      def hello_get(request):
          """HTTP Cloud Function.
          Args:
              request (flask.Request): The request object.
              <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
          Returns:
              The response text, or any set of values that can be turned into a
              Response object using `make_response`
              <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
          Note:
              For more information on how Flask integrates with Cloud
              Functions, see the `Writing HTTP functions` page.
              <https://cloud.google.com/functions/docs/writing/http#http_frameworks>
          """
          return "Hello World!"
      
      

      Go

      
      // Package helloworld provides a set of Cloud Functions samples.
      package helloworld
      
      import (
      	"fmt"
      	"net/http"
      )
      
      // HelloGet is an HTTP Cloud Function.
      func HelloGet(w http.ResponseWriter, r *http.Request) {
      	fmt.Fprint(w, "Hello, World!")
      }
      

      Java

      
      package functions;
      
      import com.google.cloud.functions.HttpFunction;
      import com.google.cloud.functions.HttpRequest;
      import com.google.cloud.functions.HttpResponse;
      import java.io.BufferedWriter;
      import java.io.IOException;
      
      public class HelloWorld implements HttpFunction {
        // Simple function to return "Hello World"
        @Override
        public void service(HttpRequest request, HttpResponse response)
            throws IOException {
          BufferedWriter writer = response.getWriter();
          writer.write("Hello World!");
        }
      }

      Ruby

      require "functions_framework"
      
      FunctionsFramework.http "hello_get" do |_request|
        # The request parameter is a Rack::Request object.
        # See https://www.rubydoc.info/gems/rack/Rack/Request
      
        # Return the response body as a string.
        # You can also return a Rack::Response object, a Rack response array, or
        # a hash which will be JSON-encoded into a response.
        "Hello World!"
      end

    関数のデプロイ

    HTTP トリガーを使用して関数をデプロイするには、サンプルコード(Java の場合は pom.xml ファイル)を含むディレクトリで次のコマンドを実行します。

    Node.js

    gcloud functions deploy helloGET \
    --runtime nodejs20 --trigger-http

    サポートされている Node.js バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    Python

    gcloud functions deploy hello_get \
    --runtime python312 --trigger-http

    サポートされている Python バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    Go

    gcloud functions deploy HelloGet \
    --runtime go121 --trigger-http

    サポートされている Go バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    Java

    gcloud functions deploy java-http-function \
    --entry-point functions.HelloWorld \
    --runtime java17 \
    --memory 512MB --trigger-http

    サポートされている Java バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    Ruby

    gcloud functions deploy hello_get --runtime ruby33 --trigger-http

    サポートされている Ruby バージョンのランタイム ID を指定して関数を実行するには、--runtime フラグを使用します。

    必要に応じて --allow-unauthenticated フラグを使用し、認証なしで関数にアクセスすることもできます。これはテストに便利ですが、公開 API やウェブサイトを作成する場合を除き、本番環境でこの設定を使用することはおすすめしません。また、会社のポリシーの設定によっては、これは機能しない可能性があります。認証が必要な関数を呼び出す方法については、呼び出しの認証をご覧ください。

    関数のトリガー

    関数に対して HTTP リクエストを実行するには、以下のコマンドを実行します。

    Node.js

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/helloGET" 

    Python

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/hello_get" 

    Go

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/HelloGet" 

    Java

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/java-http-function" 

    Ruby

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/hello_get" 

    ここで

    • REGION は関数がデプロイされるリージョンです。関数のデプロイが完了するとターミナルに表示されます。
    • PROJECT_ID は Cloud プロジェクト ID です。 関数のデプロイが完了するとターミナルに表示されます。

    ブラウザで、デプロイされた関数のエンドポイントにアクセスして、「Hello World!」メッセージを表示することもできます。

    クリーンアップ

    このチュートリアルで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、リソースを含むプロジェクトを削除するか、プロジェクトを維持して個々のリソースを削除します。

    プロジェクトの削除

    課金されないようにする最も簡単な方法は、チュートリアル用に作成したプロジェクトを削除することです。

    プロジェクトを削除するには:

    1. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    関数の削除

    Cloud Run functions を削除しても、Cloud Storage に保存されたリソースは削除されません。

    このチュートリアルで作成した Cloud Run 関数を削除するには、次のコマンドを実行します。

    Node.js

    gcloud functions delete helloGET 

    Python

    gcloud functions delete hello_get 

    Go

    gcloud functions delete HelloGet 

    Java

    gcloud functions delete java-http-function 

    Ruby

    gcloud functions delete hello_get 

    Cloud Run functions 関数は Google Cloud コンソールで削除することもできます。