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

Function Compute:SDKを使用したHTTPトリガー関数の実行

最終更新日:Sep 10, 2024

このトピックでは、SDKが提供する言語ごとのインターフェイスを使用して、HTTPトリガー (認証が必要) で設定された関数を実行する方法について説明します。

背景情報

Function Computeは、リクエストヘッダーの [許可] フィールドに基づいて、リクエストが有効かどうかを検証します。

説明

匿名アクセスを許可し、HTTPトリガーを持つ関数は検証できません。

検証に合格するには、Function Computeサーバーと一致する署名アルゴリズムを使用する必要があります。 承認フィールドが含まれていない、または無効な署名が含まれているリクエストの場合、Function ComputeHTTPステータスコード403を返します。 詳細については、「署名認証」をご参照ください。

Function Compute SDKは、手動計算なしでHTTPトリガー関数を実行するためのAPIを提供します。 詳細は、「SDK」をご参照ください。

Java

  1. 次のコードを実行して、Mavenの依存関係をpom.xmlファイルに追加します。

        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>aliyun-java-sdk-fc</artifactId>
          <version>1.8.32</version>
        </dependency>
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>2.0.20</version>
        </dependency>
  2. Java SDKを使用してHTTPトリガーをトリガーします。 次のサンプルコードに例を示します。 詳細については、「SDKソースコード」をご参照ください。

    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.fc.client.FunctionComputeClient;
    import com.aliyuncs.fc.model.HttpAuthType;
    import com.aliyuncs.fc.model.HttpMethod;
    import com.aliyuncs.fc.request.*;
    import com.aliyuncs.fc.response.*;
    import java.io.IOException;
    import java.security.InvalidKeyException;
    
    public class testJavaSDK {
        private static final String REGION = "cn-hangzhou";
        private static final String SERVICE_NAME = "<Your serviceName>";
        private static final String FUNCTION_NAME = "<Your functionName>";
        /*
        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 in 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 ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your local environment before you run the sample code. 
        The ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions in the runtime of Function Compute. 
        */
        public static void main(final String[] args) throws IOException, InvalidKeyException, IllegalStateException {
            String accountId = "XXX";
            String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String accessSecretKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            FunctionComputeClient fcClient = new FunctionComputeClient(REGION, accountId, accessKey, accessSecretKey);
            HttpInvokeFunctionRequest request = new HttpInvokeFunctionRequest(SERVICE_NAME,FUNCTION_NAME, HttpAuthType.FUNCTION, HttpMethod.POST, null);
            JSONObject object = new JSONObject();
            object.put("string","string");
            object.put("int","123");
            String payload = object.toJSONString();
            request.setPayload(payload.getBytes());
            request.setHeader("Content-Type", "application/json");
            InvokeFunctionResponse invkResp = fcClient.invokeFunction(request);
            System.out.println(new String(invkResp.getContent()));
        }
    }

Python

  1. 次のコードを実行して依存関係をインストールします。

    pip install aliyun-fc2
  2. Python SDKを使用してHTTPトリガーをトリガーします。 次のサンプルコードに例を示します。 詳細については、「SDKソースコード」をご参照ください。

    # -*- coding: utf-8 -*-
    import fc2
    import os
    
    # 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 local environment before you run the sample code. 
    # In the runtime 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. 
    accessKeyID=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID')
    accessKeySecret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    
    endpoint='<Your Endpoint>'
    
    client = fc2.Client(
        endpoint=endpoint,
        accessKeyID=accessKeyID,
        accessKeySecret=accessKeySecret)
    req = client.do_http_request( "method", "serviceName", "functionName",
             "path", headers={}, params=None, body=bytes('hello_world'.encode('utf-8')))
    print (req.status_code)

    エンドポイントの設定方法の詳細については、「エンドポイント」をご参照ください。

PHP

  1. 次の方法で依存関係をインストールできます。

    • Composerコマンドを実行して依存関係をインストールします。

      composer require aliyunfc/fc-php-sdk
    • Function Compute SDK for PHPの依存関係をcomposer.jsonファイルで宣言します。

      "require":{
          "aliyunfc/fc-php-sdk": "~1.2"
      }
  2. composer installコマンドを実行して、依存関係をインストールします。 Composerのインストール後、依存関係をPHPコードにインポートします。

    require_once __DIR__ . '/vendor/autoload.php';
  3. PHP SDKを使用してHTTPトリガーをトリガーします。 次のサンプルコードに例を示します。 詳細については、「SDKソースコード」をご参照ください。

    <?php
    require_once __DIR__ . '/vendor/autoload.php';
    use AliyunFC\Client;
    
    # 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 local environment before you run the sample code. 
    # In the runtime 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. 
    
    $fcClient = new Client([
      "endpoint" => '<Your Endpoint>',
      "accessKeyID" => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
      "accessKeySecret" => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    ]);
    $res = $fcClient->doHttpRequest("method", "serviceName", "functionName", "path", $headers = [], $unescapedQueries = [], $data = null);
    $s = $res->getStatusCode();
    $data = $res->getBody()->getContents();
    var_dump($s);
    var_dump($data);

    エンドポイントの設定方法の詳細については、「エンドポイント」をご参照ください。

Node.js

  1. 次のコードを実行して依存関係をインストールします。

    npm install @alicloud/fc2 --save
  2. Node.js SDKを使用して、HTTPトリガーをトリガーします。 次のサンプルコードは、GETリクエストの例を示しています。 詳細については、「サポートされているSDK」をご参照ください。

    'use strict';
    var FCClient = require('@alicloud/fc2');
    /*
    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 in 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. 
    The ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions in the runtime of Function Compute. 
    */
    var client = new FCClient('<Your AccountID>', {
      accessKeyID: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
      region: '<Your Region>',
    });
    async function test () {
      try {
          var headers ={}
          var resp = await client.get('/proxy/${serviceName}/${functionName}/${path}',null,headers )
          console.log('invoke function: %j', resp);
      } catch (err) {
          console.error(err);
        }
    }
    test().then();

. NETコア

  1. 次のコードを実行して、次のパッケージに追加します。csproj依存関係をインストールするファイル。

    <ItemGroup>
        <PackageReference Include="Aliyun.FC.SDK.NetCore" Version="1.0.0" />
    </ItemGroup>
  2. を使用します。HTTPトリガーをトリガーするためのNET Core SDK。 次のサンプルコードに例を示します。 詳細については、「SDKソースコード」をご参照ください。

    using System;
    using System.Collections.Generic;
    using Aliyun.FunctionCompute.SDK.Client;
    using Aliyun.FunctionCompute.SDK.Request;
    
    namespace mynetcore{
        class Program
        {
            static void Main(string[] args)
            {
                /*
                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 in 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. 
                The ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions in the runtime of Function Compute. 
                */
                var accessKeyID = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                var accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    
                var fcClient = new FCClient("<Your Region>", "<Your AccountID>", accessKeyID, accessKeySecret);
                var customHeaders = new Dictionary<string, string> {
    
                };
                Dictionary<string, string[]> unescapedQueries = new Dictionary<string, string[]> {
    
                };
                byte[] payload = new byte[]{
    
                };
    
               var resposnse = fcClient.InvokeHttpFunction(new HttpInvokeFunctionRequest("serviceName", "functionName", "method", "path", "qualifier", payload, unescapedQueries ,customHeaders));
                Console.WriteLine(resposnse.StatusCode);
            }
        }
    }

Go

  1. 次のコードを実行して依存関係をインストールします。

    go get -u github.com/aliyun/fc-go-sdk
  2. Go SDKを使用してHTTPトリガーをトリガーします。 次のサンプルコードに例を示します。 詳細については、「SDKソースコード」をご参照ください。

    import (
        "io"
        "net/http"
        "os"
        "time"
        fc "github.com/aliyun/fc-go-sdk"
    )
    
    func doPost(serviceName, functionName, qualifier, path string,
        headers http.Header, queries map[string][]string, bodyReader io.Reader) (*http.Response, error) {
    
        /*
            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 in 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. 
            The ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions in the runtime of Function Compute. 
       */
        accessKeyID := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
        accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    
        fcClient, _ := fc.NewClient("<Your AccountID>", "2016-08-15", accessKeyID, accessKeySecret)
        method := http.MethodPost
        expires := time.Now().Add(5 * time.Minute)
        input := fc.NewSignURLInput(method, serviceName, functionName, expires)
        input.WithQualifier(qualifier).WithHeader(headers).WithQueries(queries).WithEscapedPath(path)
        url, err := fcClient.SignURL(input)
        if err != nil {
            return nil, err
        }
        req, err := http.NewRequest(method, url, bodyReader)
        for k, values := range headers {
            for _, v := range values {
                req.Header.Add(k, v)
            }
        }
        c := &http.Client{}
        return c.Do(req)
    }