Function Compute SDKs handle request signing automatically, so you don't need to implement the signature algorithm yourself. This page shows how to invoke HTTP-triggered functions using the Go, Python, and Java SDKs.
How it works
Function Compute validates each incoming request against the Authorization header. If the header is missing or contains an invalid signature, Function Compute returns HTTP status code 403. For more information about signature algorithms, see Signature authentication.
The SDKs implement the signature algorithm internally. Golang, Python, and Java runtimes of Function Compute support signed invocations of HTTP triggers. Pick the invocation approach that matches your use case:
| Approach | When to use |
|---|---|
| Authenticated — SDK signs the request | Testing with authentication |
| Anonymous — no signature required | Testing an HTTP trigger configured with Authentication set to No |
| Integration — SDK signs, custom HTTP client sends | Production, when you need full control over the HTTP client for performance or extensibility |
If you set Authentication to No when configuring an HTTP trigger, the trigger accepts requests without a signature.
For the full list of available SDKs, see SDKs.
Prerequisites
Before you begin, ensure that you have:
An Alibaba Cloud account with Function Compute enabled
An HTTP-triggered function deployed in Function Compute
The
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETenvironment variables set in your local environment
Go
For additional utilities, see Go helper library.
Install the SDK for Go
Install the package using Go modules:
go get -u github.com/alibabacloud-go/fc-open-20210406Authenticated invocation
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() {
// Load credentials from environment variables.
// Avoid hardcoding AccessKey credentials in project code.
// In Function Compute runtimes, these variables are set automatically
// after you configure execution permissions.
ak := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
sk := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
url := os.Getenv("url")
config := &openapi.Config{}
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))
}Anonymous invocation
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() {
// Load credentials from environment variables.
// Avoid hardcoding AccessKey credentials in project code.
// In Function Compute runtimes, these variables are set automatically
// after you configure execution permissions.
ak := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
sk := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
url := os.Getenv("url")
config := &openapi.Config{}
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))
}Integration (custom HTTP client)
Use SignRequest to sign the request, then send it with your own HTTP client.
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() {
// Load credentials from environment variables.
// Avoid hardcoding AccessKey credentials in project code.
// In Function Compute runtimes, these variables are set automatically
// after you configure execution permissions.
ak := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
sk := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
url := os.Getenv("url")
config := &openapi.Config{}
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)
}
// Sign the request, then send it with the standard HTTP client.
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
For additional utilities, see Python helper library.
Install the SDK for Python
Install the package using pip:
pip install -U alibabacloud_fc_open20210406Authenticated invocation
# -*- coding: utf-8 -*-
import os
from alibabacloud_fc_open20210406.client import Client
from alibabacloud_tea_openapi import models as open_api_models
# Load credentials from environment variables.
# Avoid hardcoding AccessKey credentials in project code.
# In Function Compute runtimes, these variables are set automatically
# after you configure 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"}
)Anonymous invocation
import os
from alibabacloud_fc_open20210406.client import Client
from alibabacloud_tea_openapi import models as open_api_models
# Load credentials from environment variables.
# Avoid hardcoding AccessKey credentials in project code.
# In Function Compute runtimes, these variables are set automatically
# after you configure 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"}
)Integration (custom HTTP client)
Use sign_request to sign a requests.Request object, then send it with your own session.
import requests
import os
from alibabacloud_fc_open20210406.client import Client
from alibabacloud_tea_openapi import models as open_api_models
# Load credentials from environment variables.
# Avoid hardcoding AccessKey credentials in project code.
# In Function Compute runtimes, these variables are set automatically
# after you configure 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, sign it, then send with a custom session.
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
For additional utilities, see Java helper library.
Install the SDK for Java
Manage dependencies using Maven or Gradle. The following shows the Maven coordinates:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>fc_open20210406</artifactId>
<!-- Use the latest version. -->
<version>2.0.4</version>
</dependency>Authenticated invocation
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 {
// Load credentials from environment variables.
// Avoid hardcoding AccessKey credentials in project code.
// In Function Compute runtimes, these variables are set automatically
// after you configure 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());
}
}
}Anonymous invocation
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 {
// Load credentials from environment variables.
// Avoid hardcoding AccessKey credentials in project code.
// In Function Compute runtimes, these variables are set automatically
// after you configure 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());
}
}
}Integration (custom HTTP client)
Use SignRequest to sign an OkHttp Request, then execute it with your own OkHttpClient.
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 {
// Load credentials from environment variables.
// Avoid hardcoding AccessKey credentials in project code.
// In Function Compute runtimes, these variables are set automatically
// after you configure 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 the request, then execute with your custom OkHttpClient.
request = client.SignRequest(request);
try (Response res = okHttpClient.newCall(request).execute()) {
System.out.println(res.toString());
System.out.println(res.body().string());
}
}
}FAQ
I'm getting `AttributeError: 'Client' object has no attribute 'sign_request'` when invoking an HTTP function.
This error means you're running an older version of the Function Compute SDK that doesn't include the sign_request method. Upgrade to the latest version. For the current SDK packages, see Supported SDKs.