This topic describes how to run HTTP functions by using the interfaces provided by SDKs for different languages.
Background
Function Compute verifies whether a request is valid based on the Authorization field in a request header. A request passes the verification only if the client that sends the request uses the same signature algorithm as Function Compute. If a request does not contain the Authorization header field or the Authorization header field contains an invalid signature, Function Compute returns the HTTP status code 403
. For more information about signature algorithms, see Signature authentication.
Function Compute SDKs provide interfaces to run HTTP functions, and signature algorithms are implemented in these SDKs. This way, you do not need to manually calculate signatures. For more information, see SDKs.
If you set the Authentication parameter to No when you configure an HTTP trigger, you can access functions anonymously. In this case, no verification is required, and the signature is not calculated.
Scenarios
Golang, Python, and Java runtimes of Function Compute support signed invocations of HTTP triggers. You can use Function Compute SDKs in the following scenarios:
Invoke an HTTP trigger when signature verification is used. This is recommended in test scenarios.
Invoke an HTTP trigger when signature verification is not used. This is recommended in test scenarios.
In an integration scenario. Sign an HTTP request and use a custom HTTP client to process the signed request to achieve the optimal performance and extensibility. This is recommended in production environments.
Scenarios
Golang
For more information, see Go.
Install the SDK for Go
The following code describes how to install the SDK for Go by using Go modules.
# install alibabacloud_fc_open20210406
go get -u github.com/alibabacloud-go/fc-open-20210406
Use the SDK for Go
Sample code when signature verification is used
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)) }
Sample code when signature verification is not used
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)) }
Sample code in integration scenarios
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
For more information, see Python.
Install the SDK for Go
The following code describes how to install the SDK for Python dependency by using pip.
# install alibabacloud_fc_open20210406
pip install -U alibabacloud_fc_open20210406
Use the SDK for Go
Sample code when signature verification is used
# -*- 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"})
Sample code when signature verification is not used
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"})
Sample code in integration scenarios
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
For more information, see Java.
Install the SDK for Go
You can manage dependencies by using Maven or Gradle. The following code describes the Maven coordinates:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>fc_open20210406</artifactId>
<!-- use the latest version instead -->
<version>2.0.4</version>
</dependency>
Use the SDK for Go
Sample code when signature verification is used
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()); } } }
Sample code when signature verification is not used
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()); } } }
Sample code in integration scenarios
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()); } } }
FAQ
What do I do if an error, such as a method does not exist, is reported when I run an HTTP function?
Problem description:
AttributeError: 'Client' object has no attribute 'sign_request'
is reported when a user runs an HTTP function.Possible cause: An earlier version of Function Compute SDK is used in the code.
Solution: We recommend that you upgrade the Function Compute SDK to the latest version. For more information, see Supported SDKs.