All Products
Search
Document Center

Function Compute (2.0):Use SDKs to execute HTTP trigger functions

Last Updated:Jun 19, 2023

This topic describes how to execute a function configured with HTTP triggers (authentication required) by using the interfaces provided by the SDKs for different languages.

Background information

Function Compute verifies whether a request is valid based on the Authorization field in the request header.
Note Functions that allow anonymous access and that have HTTP triggers cannot be verified.

A signature algorithm consistent with the Function Compute server must be used to pass the verification. For requests that do not contain the Authorization field or contain invalid signatures, Function Compute returns HTTP status code 403. For more information, see Signature authentication.

Function Compute SDKs provide APIs to execute HTTP trigger functions without manual calculation. For more information, see SDKs.

Java

  1. Run the following code to add Maven dependencies to the pom.xml file.
        <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. Use the Java SDK to trigger the HTTP trigger. The following sample code provides an example. For more information, see SDK source code.
    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. Run the following code to install dependencies:
    pip install aliyun-fc2
  2. Use the Python SDK to trigger the HTTP trigger. The following sample code provides an example. For more information, see SDK source code.
    # -*- 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)

    For more information about how to configure endpoints, see Endpoints.

PHP

  1. You can install dependencies in the following ways:
    • Run the Composer command to install dependencies.
      composer require aliyunfc/fc-php-sdk
    • Declare dependencies on Function Compute SDK for PHP in the composer.json file.
      "require":{
          "aliyunfc/fc-php-sdk": "~1.2"
      }
  2. Run the composer install command to install dependencies. After Composer is installed, import dependencies to PHP code.
    require_once __DIR__ . '/vendor/autoload.php';
  3. Use the PHP SDK to trigger the HTTP trigger. The following sample code provides an example. For more information, see SDK source code.
    <?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);

    For more information about how to configure endpoints, see Endpoints.

Node.js

  1. Run the following code to install dependencies:
    npm install @alicloud/fc2 --save
  2. Use the Node.js SDK to trigger the HTTP trigger. The following sample code provides an example of GET requests. For more information, see Supported SDKs.
    '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 Core

  1. Run the following code to add the following package to the .csproj file to install dependencies.
    <ItemGroup>
        <PackageReference Include="Aliyun.FC.SDK.NetCore" Version="1.0.0" />
    </ItemGroup>
  2. Use the .NET Core SDK to trigger the HTTP trigger. The following sample code provides an example. For more information, see SDK source code.
    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. Run the following code to install dependencies:
    go get -u github.com/aliyun/fc-go-sdk
  2. Use the Go SDK to trigger the HTTP trigger. The following sample code provides an example. For more information, see SDK source code.
    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)
    }