すべてのプロダクト
Search
ドキュメントセンター

Function Compute:SDKを使用したHTTP関数の実行

最終更新日:Sep 10, 2024

このトピックでは、SDKが提供するさまざまな言語のインターフェイスを使用してHTTP関数を実行する方法について説明します。

背景

Function Computeは、リクエストヘッダーの [許可] フィールドに基づいて、リクエストが有効かどうかを検証します。 リクエストを送信するクライアントがFunction Computeと同じ署名アルゴリズムを使用している場合にのみ、リクエストは検証に合格します。 リクエストにAuthorizationヘッダーフィールドが含まれていない場合、またはAuthorizationヘッダーフィールドに無効な署名が含まれている場合、Function ComputeHTTPステータスコード403を返します。 署名アルゴリズムの詳細については、「署名認証」をご参照ください。

Function Compute SDKはHTTP関数を実行するためのインターフェイスを提供し、署名アルゴリズムはこれらのSDKに実装されます。 この方法では、手動で署名を計算する必要はありません。 詳細は、「SDK」をご参照ください。

説明

HTTPトリガーを設定するときに [認証] パラメーターを [いいえ] に設定すると、匿名で関数にアクセスできます。 この場合、検証は不要であり、署名は計算されない。

シナリオ

Function ComputeのGolang、Python、およびJavaランタイムは、HTTPトリガーの署名付き呼び出しをサポートしています。 次のシナリオでFunction Compute SDKを使用できます。

  • 署名検証が使用されているときにHTTPトリガーを呼び出します。 これは、テストシナリオで推奨されます。

  • 署名検証を使用しない場合は、HTTPトリガーを呼び出します。 これは、テストシナリオで推奨されます。

  • 統合シナリオでは。 HTTPリクエストに署名し、カスタムHTTPクライアントを使用して署名済みリクエストを処理し、最適なパフォーマンスと拡張性を実現します。 これは本番環境で推奨されます。

シナリオ

Golang

詳細については、「Go」をご参照ください。

Go用SDKのインストール

次のコードでは、Goモジュールを使用してGo用SDKをインストールする方法について説明します。

# install alibabacloud_fc_open20210406
go get -u github.com/alibabacloud-go/fc-open-20210406

Go用SDKの使用

  • 署名検証を使用する場合のサンプルコード

    package main
    
    import (
        "fmt"
        "net/http"
        "net/http/httputil"
        "os"
    
        openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
        client "github.com/alibabacloud-go/fc-open-20210406/client"
    )
    
    func main() {
        config := &openapi.Config{}
        /*
            The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. 
            We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
            In this example, the AccessKey pair is saved to the environment variables for authentication. 
            Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your local environment before you run the sample code. 
            In runtimes of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
      */
        ak := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
        sk := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        url := os.Getenv("url")
    
        config.SetAccessKeyId(ak)
        config.SetAccessKeySecret(sk)
        config.SetRegionId("cn-hangzhou")
        c, err := client.NewClient(config)
        if err != nil {
            panic(err)
        }
        method := "POST"
        headers := &http.Header{}
        headers.Add("k1", "v1")
        resp, err := c.InvokeHTTPTrigger(&url, &method, []byte("abc"), headers)
        if err != nil {
            panic(err)
        }
        str, _ := httputil.DumpResponse(resp, true)
        fmt.Printf("response: %+v\n", string(str))
    }
  • 署名検証を使用しない場合のサンプルコード

    package main
    
    import (
    	"fmt"
    	"net/http"
    	"net/http/httputil"
    	"os"
    
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	client "github.com/alibabacloud-go/fc-open-20210406/client"
    )
    
    func main() {
    	config := &openapi.Config{}
    	/*
    		The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. 
    		We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
    		In this example, the AccessKey pair is saved to the environment variables for authentication. 
    		Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your local environment before you run the sample code. 
    		In runtimes of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
          */
    	ak := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    	sk := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    	url := os.Getenv("url")
    
    	config.SetAccessKeyId(ak)
    	config.SetAccessKeySecret(sk)
    	config.SetRegionId("cn-hangzhou")
    	c, err := client.NewClient(config)
    	if err != nil {
    		panic(err)
    	}
    	method := "POST"
    	headers := &http.Header{}
    	headers.Add("k1", "v1")
    	resp, err := c.InvokeAnonymousHTTPTrigger(&url, &method, []byte("abc"), headers)
    	if err != nil {
    		panic(err)
    	}
    	str, _ := httputil.DumpResponse(resp, true)
    	fmt.Printf("response: %+v\n", string(str))
    }
  • 統合シナリオのサンプルコード

    package main
    
    import (
    	"fmt"
    	"net/http"
    	"net/http/httputil"
    	"os"
    
    	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
    	client "github.com/alibabacloud-go/fc-open-20210406/v2/client"
    )
    
    func main() {
    	config := &openapi.Config{}
    	/*
    	The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. 
    	We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
    	In this example, the AccessKey pair is saved to the environment variables for authentication. 
    	Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your on-premises environment before you run the sample code. 
            In runtimes of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
           */
    	ak := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    	sk := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    	url := os.Getenv("url")
    
    	config.SetAccessKeyId(ak)
    	config.SetAccessKeySecret(sk)
    	config.SetRegionId("cn-hangzhou")
    	c, err := client.NewClient(config)
    	if err != nil {
    		panic(err)
    	}
    	method := "GET"
    	request, err := http.NewRequest(method, url, nil)
    	if err != nil {
    		panic(err)
    	}
    	request, err = c.SignRequest(request)
    	if err != nil {
    		panic(err)
    	}
    	resp, err := http.DefaultClient.Do(request)
    	if err != nil {
    		panic(err)
    	}
    	str, _ := httputil.DumpResponse(resp, true)
    	fmt.Printf("response: %+v\n", string(str))
    }                  

Python

詳細については、「Python」をご参照ください。

Go用SDKのインストール

次のコードでは、pipを使用してPython依存関係のSDKをインストールする方法について説明します。

# install alibabacloud_fc_open20210406
pip install -U alibabacloud_fc_open20210406

Go用SDKの使用

  • 署名検証を使用する場合のサンプルコード

    # -*- coding: utf-8 -*-
    import os
    
    from alibabacloud_fc_open20210406.client import Client
    from alibabacloud_tea_openapi import models as open_api_models
    
    # The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. 
    # We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
    # In this example, the AccessKey pair is saved to the environment variables for authentication. 
    # Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your on-premises environment before you run the sample code. 
    # In runtimes of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
    ak = os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID')
    sk = os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    url = os.getenv('url')
    
    client = Client(config=open_api_models.Config(access_key_id=ak,
                                                  access_key_secret=sk,
                                                  region_id='cn-hangzhou'))
    
    resp = client.invoke_httptrigger(url=url,
                                     method="GET",
                                     body="anything".encode(encoding='utf-8'),
                                     headers={"k1": "v1", "k2": "v2"})
  • 署名検証を使用しない場合のサンプルコード

    import os
    
    from alibabacloud_fc_open20210406.client import Client
    from alibabacloud_tea_openapi import models as open_api_models
    
    # The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. 
    # We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
    # In this example, the AccessKey pair is saved to the environment variables for authentication. 
    # Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your on-premises environment before you run the sample code. 
    # In runtimes of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
    ak = os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID')
    sk = os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    url = os.getenv('url')
    
    client = Client(config=open_api_models.Config(access_key_id=ak,
                                                  access_key_secret=sk,
                                                  region_id='cn-hangzhou'))
    
    resp = client.invoke_anonymous_httptrigger(url=url,
                                     method="GET",
                                     body="anything".encode(encoding='utf-8'),
                                     headers={"k1": "v1", "k2": "v2"})
  • 統合シナリオのサンプルコード

    import requests
    import os
    
    from alibabacloud_fc_open20210406.client import Client
    from alibabacloud_tea_openapi import models as open_api_models
    
    # The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. 
    # We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
    # In this example, the AccessKey pair is saved to the environment variables for authentication. 
    # Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your on-premises environment before you run the sample code. 
    # In runtimes of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
    ak = os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID')
    sk = os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    url = os.getenv('url')
    
    client = Client(config=open_api_models.Config(access_key_id=ak,
                                                  access_key_secret=sk,
                                                  region_id='cn-hangzhou'))
    
    # build your own request
    req = requests.Request(
        url=url,
        method='GET'
    )
    req = client.sign_request(req)
    with requests.Session() as s:
        prep=s.prepare_request(req)
        resp = s.send(prep)

Java

詳細は、「Java」をご参照ください。

Go用SDKのインストール

MavenまたはGradleを使用して依存関係を管理できます。 次のコードは、Maven座標を説明しています。

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>fc_open20210406</artifactId>
  <!-- use the latest version instead -->
  <version>2.0.4</version>
</dependency>

Go用SDKの使用

  • 署名検証を使用する場合のサンプルコード

    package com.aliyun.example;
    
    import com.aliyun.fc_open20210406.Client;
    import com.aliyun.teaopenapi.models.Config;
    import okhttp3.Headers;
    import okhttp3.Response;
    
    import java.nio.charset.StandardCharsets;
    
    
    public class Main {
        public static void main(String[] args) throws Exception {
            /*
            The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. 
            We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
            In this example, the AccessKey pair is saved to the environment variables for authentication. 
            Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your on-premises environment before you run the sample code. 
            In runtimes of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
         	 	*/
            String ak = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String sk = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            String url = System.getenv("url");
            Config config = new Config().setAccessKeyId(ak).setAccessKeySecret(sk).setRegionId("cn-hangzhou");
    
            Client client = new Client(config);
            try (Response res = client.InvokeHTTPTrigger(url, "POST", "mybodystring".getBytes(StandardCharsets.UTF_8), new Headers.Builder().build())) {
                System.out.println(res.toString());
                System.out.println(res.body().string());
            }
        }
    }
  • 署名検証を使用しない場合のサンプルコード

    package com.aliyun.example;
    
    import com.aliyun.fc_open20210406.Client;
    import com.aliyun.teaopenapi.models.Config;
    import okhttp3.Headers;
    import okhttp3.Response;
    
    import java.nio.charset.StandardCharsets;
    
    public class Main {
        public static void main(String[] args) throws Exception {
            /*
            The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. 
            We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
            In this example, the AccessKey pair is saved to the environment variables for authentication. 
            Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables before you run the sample code. 
            In runtimes of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
         	*/
            String ak = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String sk = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            String url = System.getenv("url");
            Config config = new Config().setAccessKeyId(ak).setAccessKeySecret(sk).setRegionId("cn-hangzhou");
    
            Client client = new Client(config);
            try (Response res = client.InvokeAnonymousHTTPTrigger(url, "POST", "mybodystring".getBytes(StandardCharsets.UTF_8), new Headers.Builder().build())) {
                System.out.println(res.toString());
                System.out.println(res.body().string());
            }
        }
    }
  • 統合シナリオのサンプルコード

    package com.aliyun.example;
    
    import com.aliyun.fc_open20210406.Client;
    import com.aliyun.tea.okhttp.OkHttpClientBuilder;
    import com.aliyun.teaopenapi.models.Config;
    import okhttp3.*;
    
    import java.nio.charset.StandardCharsets;
    
    
    public class Main {
        public static void main(String[] args) throws Exception {
            /*
            The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. 
            We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
            In this example, the AccessKey pair is saved to the environment variables for authentication. 
            Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your on-premises environment before you run the sample code. 
            In runtimes of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
         	*/
            String ak = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String sk = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            String url = System.getenv("url");
            Config config = new Config().setAccessKeyId(ak).setAccessKeySecret(sk).setRegionId("cn-hangzhou");
    
            Client client = new Client(config);
            OkHttpClient okHttpClient = new OkHttpClientBuilder().buildOkHttpClient();
    
            Request request = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(MediaType.parse("application/json"),
                            "mybodystring".getBytes(StandardCharsets.UTF_8)))
                    .build();
    
            // sign your request
            request = client.SignRequest(request);
            try (Response res = okHttpClient.newCall(request).execute()) {
                System.out.println(res.toString());
                System.out.println(res.body().string());
            }
        }
    }

よくある質問

HTTP関数を実行したときにメソッドが存在しないなどのエラーが報告された場合はどうすればよいですか?

  • 問題の説明: AttributeError: 'Client' object has no attribute 'sign_request' は、ユーザーがHTTP関数を実行すると報告されます。

  • 考えられる原因: 以前のバージョンのFunction Compute SDKがコードで使用されています。

  • 解決策: Function Compute SDKを最新バージョンにアップグレードすることを推奨します。 詳細については、「サポートされているSDK」をご参照ください。