An HTTP trigger allows you to invoke a function with an HTTP request. HTTP triggers can be used in scenarios such as fast construction of web services. This topic describes the precautions, benefits, invocation methods, supported protocols, authentication methods, cross-origin resource sharing (CORS) request processing, limits, and handlers of HTTP triggers.
Precautions
- If you set Authentication to No in the trigger configuration, the HTTP trigger is anonymous. In this case, anyone can invoke your function by sending an HTTP request. This may leak URLs. To avoid URL leakage, you can use the
Authorization
field of the request header to check the validity of a request. For more information, see Signature authentication. - HTTP triggers cannot be created for custom container functions that are in the non-web server mode.
Limits
This section describes the limits on HTTP triggers and the HTTP, WebSocket, and gRPC protocols. Read this section before you configure and use HTTP triggers.
Limits on triggers
- After you configure an HTTP trigger for a function, you cannot configure other types of triggers for the function.
- You can configure only one HTTP trigger for a function.
- For each version or alias of a service, you can create only one HTTP trigger. For more information, see Manage versions and Manage aliases.
Limits on HTTP
- HTTP request limits
- You cannot create a request header that starts with x-fc- or the following request headers:
- connection
- keep-alive
- If a request exceeds one of the following limits, the system returns the
400
status code and theInvalidArgument
error.- Header size: The total size of all keys and values in the headers cannot exceed 4 KB.
- Path size: The total size of the path, including all query parameters, cannot exceed 4 KB.
- Body size: The total size of the body of a synchronous invocation request cannot exceed 32 MB. The total size of the body of an asynchronous invocation request cannot exceed 128 KB.
- You cannot create a request header that starts with x-fc- or the following request headers:
- HTTP response limits
- You cannot customize a response header that starts with x-fc- or the following headers:
- connection
- content-length
- date
- keep-alive
- server
- upgrade
- content-disposition:attachmentNote For security purposes, the server forcefully adds the content-disposition: attachment field to the response header when the default domain name aliyuncs.com of Function Compute is used. This field is used to download the returned results from the browser as an attachment. To remove this limit, you must configure a custom domain name. For more information, see Configure a custom domain name.
- If a response exceeds one of the following limits, the system returns the
502
status code and theBadResponse
error.- Header size: The total size of all keys and values in the headers cannot exceed 4 KB.
- You cannot customize a response header that starts with x-fc- or the following headers:
- Others
You can bind a custom domain name to map different HTTP paths for HTTP functions. For more information, see Configure a custom domain name. You can also use API Gateway to implement similar features by setting the backend service type to HTTP and specifying the HTTP function path as the backend service address. For more information, see Use Function Compute as the backend service of the API.
Limits on WebSocket
- Runtime: Only custom runtimes and custom container runtimes support WebSocket.
- Timeout limit: The timeout period of a WebSocket request is subject to the timeout period that is configured for a function.
- Request limits for a WebSocket handshake request:
- Request headers that start with x-fc- are not supported.
- Header size: The total size of all keys and values in the headers cannot exceed 4 KB.
- Path size: The total size of the path, including all query parameters, cannot exceed 4 KB.
- Body: The body cannot be sent in a WebSocket handshake request. If the body is sent, Function Compute ignores the request.
- Response limit for a WebSocket handshake request:
The total size of all keys and values in response headers cannot exceed 4 KB. Otherwise, the system returns the
502
status code and theBadResponse
error. - Data transmission limits for WebSocket:
After you establish a WebSocket connection, the maximum size of packets (messages) that can be sent or received at a time is 6 MB.
Limits on gRPC
- Runtime: Only custom runtimes and custom containers support gRPC.
- How to use:
- Before you use gRPC to trigger function execution, make sure that the POST method is included in Request Method of the HTTP trigger.
- Use the
fcapp.run
subdomain or a custom domain name to initiate a gRPC-based invocation.
- Timeout period: gRPC requests are subject to the timeout period configured for the function. Specifically, the maximum retention period of a streaming gRPC connection cannot exceed the value of Execution Timeout Period configured for the function.
- Data transmission of gRPC requests: After you establish a gRPC streaming connection, the upper limit of size of packets (messages) that can be sent or received at a time is 6 MB.
Benefits
You can use HTTP triggers and API Gateway triggers to create web applications. Compared with API Gateway triggers, HTTP triggers provide the following benefits:
- HTTP triggers are easier to learn, use, and debug, which helps developers quickly build web applications and APIs by using Function Compute.
- You can use HTTP triggers to optimize request processing. HTTP triggers support more efficient request and response formats. You do not need to encode or decode requests to the JSON format. This helps deliver better performance.
- You can use HTTP test tools with which you are familiar to test the features and performance of HTTP triggers in Function Compute.
- You can connect HTTP triggers to other services that support webhooks with ease, such as Alibaba Cloud CDN and Message Service (MNS).
- WebSocket is supported.
- The gRPC protocol is supported.
Invocation methods
Functions can be invoked in both synchronous and asynchronous modes. During a synchronous invocation, the result is directly returned after an event is processed by a function. During an asynchronous invocation, Function Compute persists the request and immediately returns a response without waiting for the execution of the request to complete.
Synchronous invocation
By default, an HTTP trigger invokes a function synchronously. For more information, see Synchronous invocations.
Asynchronous invocation
You can use an HTTP trigger to invoke a function asynchronously at the request level by adding the request header "X-Fc-Invocation-Type":"Async"
. After you configure an asynchronous invocation task for an HTTP function, you can add the request header "X-Fc-Stateful-Async-Invocation-Id":"g6u*****iyvhd3jk8s6bhj0hh"
to configure the invocation ID of the asynchronous invocation task. For more information about request headers, see InvokeFunction.
After the asynchronous invocation task succeeds, Function Compute returns the status code 202
, which indicates that the request is received. In addition, the system returns the request ID and stateful invocation ID based on the request header. The format is "X-Fc-Request-Id": "80bf7****281713e1", "X-Fc-Stateful-Async-Invocation-Id": "7522ba40****1c22e"
.
202
, the asynchronous invocation task fails. For more information about the causes of failed invocations, see Error handling. In some scenarios, after you submit an asynchronous invocation request, you may want Function Compute to defer the invocation. In this case, you must add the HTTP request header x-fc-async-delay
to the code. The value range of the header is (0,3600). Unit: seconds. Function Compute invokes the function after the period specified by x-fc-async-delay
elapses. For more information, see Deferred invocation of a function.
- For more information about asynchronous invocations, see Asynchronous invocations.
- For more information about asynchronous tasks, see Overview.
Supported protocols
- HTTP and HTTPS
Methods including GET, POST, PUT, DELETE, HEAD, PATCH, and OPTIONS can be used to trigger functions. The HTTP and HTTPS protocols are suitable for simple request-response scenarios. For more information, see Configure an HTTP trigger that invokes a function with HTTP requests.
- WebSocket
The GET method can be used to trigger functions. The WebSocket is suitable for scenarios such as the persistent connection and real-time messaging scenarios. For more information, see Configure an HTTP trigger for a function that is triggered by WebSocket requests.
- gRPC
The gRPC protocol can be used to trigger functions. The gRPC protocol is suitable for scenarios with low latency, high performance, and ProtoBuf-based multi-language communication. For more information, see Configure an HTTP trigger that invokes a function with gRPC requests.
Authentication
You can configure authentication policies for HTTP triggers. After you configure an authentication policy for an HTTP trigger, external requests must pass the authentication before they can be processed by functions.
Signature authentication and JSON Web Token (JWT) authentication policies can be configured for HTTP triggers.
Signature authentication
If a signature authentication policy is configured for an HTTP trigger, requests must be signed by using the assigned AccessKey IDs and AccessKey secrets. The AccessKey IDs and AccessKey secrets are passed to Function Compute for verification. For more information, see Signature authentication.
This authentication method is highly secure, but the signature algorithm must be implemented on clients, which is costly. In addition, the AccessKey IDs and AccessKey secrets are stored on clients, which leads to data leakage risks. You can use Security Token Service (STS) tokens to prevent this issue. However, certain architectural complexity is introduced.
JWT authentication
JWT is a popular and secure mechanism for API authorization and access. It is suitable for low-security client scenarios such as JavaScript or web frontend. For more information, see Configure JWT authentication for an HTTP trigger.
CORS request processing
By default, Function Compute allows you to invoke HTTP functions across origins. You can also write code about how functions process CORS requests.
Simple requests
Access-Control-Allow-*
in the function code to easily implement access control. For simple requests, Function Compute supports the following custom headers:Access-Control-Allow-Origin
Access-Control-Allow-Headers
Access-Control-Request-Method
Access-Control-Max-Age
If a request does not include the preceding custom headers, the following response headers in Function Compute are set to the values of the corresponding headers in a request.
Access-Control-Allow-Origin
: the origin header of the request.Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers
: custom headers in Function Compute.
Not-so-simple requests
A preflight request is sent for a not-so-simple request. The browser sends a preflight request by using the OPTIONS method, and then initiates the actual request to invoke the function. The rules to initiate a not-so-simple request are the same as the rules to initiate a simple request. To customize the response of a preflight request, perform the following operations:
- Add the OPTIONS method to the HTTP trigger.
- Process the OPTIONS request in the function code. You must configure the header that starts with
Access-Control-Allow-*
to control the cross-origin behavior of the function.
For a preflight request, Function Compute supports the following custom headers:
Access-Control-Allow-Origin
Access-Control-Allow-Headers
Access-Control-Request-Method
Access-Control-Max-Age
exports.handler = (req, resp, context) => {
console.log('hello world');
if (req.method === 'OPTIONS') {
// Send response to OPTIONS requests
resp.setHeader('Access-Control-Allow-Origin', 'http://www.fc.com')
resp.setHeader('Access-Control-Allow-Methods', 'POST');
resp.setHeader('Access-Control-Allow-Headers', 'Content-Type');
resp.setHeader('Access-Control-Max-Age', '3600');
resp.setStatusCode(204)
resp.send('');
} else {
resp.send("hello world");
}
}
Handler functions of HTTP triggers
HTTP
- Node.js
- Python
WebSocket
Only custom runtime and custom container environments support WebSocket. For more information, see Configure an HTTP trigger for a function that is triggered by WebSocket requests, Overview, and Overview.
gRPC
Only custom runtime and custom container environments support the gRPC protocol. For more information, see Configure an HTTP trigger that invokes a function with gRPC requests.