This topic describes how to use the APIs provided by SDKs to execute HTTP trigger functions (authentication required).

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 Configure signature authentication.

Function Compute SDKs provide APIs to execute HTTP trigger functions without manual calculation. For more information, see Supported 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.7.1</version></dependency>
    ```
  2. Run the following sample code. For more information, see Supported SDKs.
    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 = "XXX";
        private static final String FUNCTION_NAME = "XXX";
        public static void main(final String[] args) throws IOException, InvalidKeyException, IllegalStateException {
            String accountId = "XXX";
            String accessKey = "XXX";
            String accessSecretKey = "XXX";
            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. Run the following sample code. For more information, see Supported SDKs.
    # -*- coding: utf-8 -*-
    
    import fc2
    client = fc2.Client(
        endpoint='<Your Endpoint>',
        accessKeyID='<Your AccessKeyID>',
        accessKeySecret='<Your 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. You can install dependencies in the following ways:
    • Run the Composer command to install dependencies.
      composer require aliyunfc/fc-php-sdk
    • Declare dependencies on Alibaba Cloud FC SDK for PHP in the composer.json file.
      "require":{
          "aliyunfc/fc-php-sdk": "~1.2"
      }
  2. Run the composer install--no dev command to install dependencies. After Composer is installed, dependencies are imported to PHP code.
    require_once __DIR__ . '/vendor/autoload.php';
  3. Run the following sample code. For more information, see Supported SDKs.
    <?php
    require_once __DIR__ . '/vendor/autoload.php';
    use AliyunFC\Client;
    $fcClient = new Client([
      "endpoint" => '<Your Endpoint>',
      "accessKeyID" =>'<Your AccessKeyID>',
      "accessKeySecret" =>'<Your AccessKeySecret>'
    ]);
    $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. Run the following code to install dependencies:
    npm install @alicloud/fc2 --save
  2. Run the following sample code to invoke GET requests. For more information, see Supported SDKs.
    'use strict';
    var FCClient = require('@alicloud/fc2');
    var client = new FCClient('<account id>', {
      accessKeyID: '<access key id>',
      accessKeySecret: '<access key secret>',
      region: 'cn-shanghai',
    });
    async function test () {
      try {
          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 package of installation dependencies to the .csproj file.
    <ItemGroup>
        <PackageReference Include="Aliyun.FC.SDK.NetCore" Version="1.0.0" />
    </ItemGroup>
  2. Run the following sample code. For more information, see Supported SDKs.
    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)
            {
                var fcClient = new FCClient("region", "<account id>", "<access key id>", "<access key secret>");
                var customHeaders = new Dictionary<string, string> {
    
                };
                Dictionary<string, string[]> unescapedQueries = new Dictionary<string, string[]> 
               {
    
                };
               var resposnse = fcClient.InvokeHttpFunction(new HttpInvokeFunctionRequest(string serviceName, string functionName, string method, string path = null,  string qualifier = null, byte[] payload = null, unescapedQueries , Dictionary<string, string> customHeaders = null));
                Console.WriteLine(resposnse.StatusCode);
            }
        }
    }