Function Compute supports HTTP triggers. Functions for which HTTP triggers are configured can be triggered and executed by using HTTP requests. The function is similar to a web server, which receives HTTP requests and returns responses to the caller. This topic describes how to configure an HTTP trigger that invokes a function with HTTP requests in the Function Compute console.
Prerequisites
Create a serviceBackground information
The method that is used to create an HTTP trigger is different from the method that is used to create other types of triggers. After you create an HTTP function, an HTTP trigger is automatically created for the function. For other types of triggers, you must manually create the triggers based on the trigger sources.Step 1: Create a trigger
- Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
- In the top navigation bar, select a region. On the Services page, click the desired service.
- On the Functions page, click Create Function.
- On the Create Function page, select Use Built-in Runtime and configure the parameters of the function. The following table describes the parameters that you must configure. Retain the default values for other parameters. For more information, see Create a function.
Parameter Description Basic Settings Function Name Specify the name of the function. Request Type Select HTTP Requests. Trigger Configurations (optional) Name Specify the name of the trigger. Disable Internet URL By default, this parameter is set to No and public domain names are allowed to access the trigger. If you select Yes, no public domain name is provided for the created HTTP trigger. In this case, the error access denied due to function internet URL is disable
is reported if you use the public domain name to invoke the function. The access is not affected if the domain name is customized.Authentication By default, this parameter is set to No, and the system does not authenticate the HTTP requests and supports anonymous access to the trigger. If you select Yes, the system authenticates the HTTP requests and does not support anonymous access. This enhances the security. Request Method Specify the methods that can be used to trigger the HTTP trigger. You can modify the settings of the created HTTP trigger based on your business requirements, including the Disable Internet URL, Authentication, and Request Method parameters.
Step 2: Write and deploy code
After the HTTP trigger is created, you can write the code for the function.
var getRawBody = require('raw-body')
module.exports.handler = function (request, response, context) {
// get request info
getRawBody(request, function (err, data) {
var params = {
path: request.path,
queries: request.queries,
headers: request.headers,
method: request.method,
body: data,
url: request.url,
clientIP: request.clientIP,
}
// you can deal with your own logic here
// set response
var respBody = new Buffer.from(JSON.stringify(params));
// var respBody = new Buffer( )
response.setStatusCode(200)
response.setHeader('content-type', 'application/json')
response.send(respBody)
})
};
# -*- coding: utf-8 -*-
import json
HELLO_WORLD = b"Hello world!\n"
def handler(environ, start_response):
request_uri = environ['fc.request_uri']
response_body = {
'uri':environ['fc.request_uri'],
'method':environ['REQUEST_METHOD']
}
# do something here
status = '200 OK'
response_headers = [('Content-type', 'text/json')]
start_response(status, response_headers)
# Python2
return [json.dumps(response_body)]
# Python3 tips: When using Python3, the str and bytes types cannot be mixed.
# Use str.encode() to go from str to bytes
# return [json.dumps(response_body).encode()]
<?php
use RingCentral\Psr7\Response;
function handler($request, $context): Response{
/*
$body = $request->getBody()->getContents();
$queries = $request->getQueryParams();
$method = $request->getMethod();
$headers = $request->getHeaders();
$path = $request->getAttribute("path");
$requestURI = $request->getAttribute("requestURI");
$clientIP = $request->getAttribute("clientIP");
*/
return new Response(
200,
array(
"custom_header1" => "v1",
"custom_header2" => ["v2", "v3"],
),
"hello world"
);
}
Step 3: Test the function
Method 1: Test the function in the Function Compute console
- Synchronous invocation
Click Test Function on the Code tab.
- Asynchronous invocation
Click the
icon next to Test Function, select Asynchronous Invocation, and then click Test Function.
Method 2: Test the function in a browser
You can use one of the following methods to obtain the URL of an HTTP trigger.
- For a new HTTP trigger, we recommend that you use the subdomain that is assigned by Function Compute to the HTTP trigger as the HTTP trigger URL.
Subdomain format:
<subdomain>.<region_id>.fcapp.run/[action?queries]
Example:
funcname-svcname-khljsjksld.cn-shanghai.fcapp.run/action?hello=world
Note You can also assemble a URL for an existing HTTP trigger based on the assembly rule. We recommend that you test the function by using the HTTP trigger URL that contains thesubdomain
assigned by Function Compute to the new HTTP trigger in Function Compute. This helps prevent the404
error and the coupling of Function Compute service names and function names in the code. This also helps improve the portability of the code. For more information about the404
error, see What do I do if a 404 error occurs when I use a browser or the cURL tool to access a function?. - For an existing HTTP trigger, you can generate an HTTP trigger URL based on the assembly rule.
Assembly rule:
<account_id>.<region_id>.fc.aliyuncs.com/<version>/proxy/<serviceName>/<functionName>/[action?queries]
Example:
164901546557****.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/serviceName/functionName/action?hello=world
The following table describes the parameters.
Parameter Description account_id The ID of the Alibaba Cloud account. You can obtain the ID of your Alibaba Cloud account on the Security Settings page in the Alibaba Cloud Management Console. If you log on as a RAM user, move the pointer over your profile picture in the upper-right corner of the console to obtain the ID of your Alibaba Cloud account.
region_id The region where the Function Compute service resides. version The version of the Function Compute API. serviceName The name of the service. functionName The name of the function. action The custom request path. queries The query parameter.
Method 3: Use cURL to test the function
- Synchronous invocationRun the following command. After the command is executed, the result is returned.
curl -v https://http-***.cn-shenzhen.fcapp.run/$path
- Asynchronous invocationRun the following command. After the command is executed, the result that is returned indicates whether Function Compute receives the asynchronous invocation request. If the status code
202
is returned, the asynchronous invocation request is successful. If another status code is returned, an exception occurs during the asynchronous invocation. For more information about error codes, see Troubleshooting in FAQ.curl -v -H "X-Fc-Invocation-Type: Async" https://http-***.cn-shenzhen.fcapp.run/$path
(Optional) Use API Gateway to protect HTTP functions
By default, Function Compute does not authenticate HTTP requests and supports anonymous access to HTTP functions. This means that anyone can send an HTTP request to invoke your function. To prevent waste of resources and security risks caused by the access of unauthorized users, you can connect HTTP functions to API Gateway while you enable identity authentication. You can use the IP-based access control plug-ins, JWT authentication plug-ins, or basic authentication plug-ins of API Gateway to protect your HTTP functions.
- In the Function Compute console, find the desired HTTP function. On the function details page, click the Triggers tab. Then, edit the HTTP trigger and select Yes for Authentication.
- Log on to the API Gateway console and switch to the region where the HTTP function resides.
- Create a group. For more information, see Create a group.
- Resolve your domain name to the second-level domain name provided by API Gateway by using CNAME. For more information, see Add a CNAME record for a domain name.
- Create an API. The following items describe how to configure the main parameters. Retain the default values or configure custom values for other parameters based on your business requirements. For more information, see Create an API.
- Security Authentication: Select No Authentication. Plug-ins will be used for authentication.
- Request Path: Enter the root directory /and select Match All Subpaths.
- HTTP Method: Select ANY.
- Request Mode: Select Passthrough.
- Backend Service Type: Select Function Compute.
- Function Type: Select HTTP Function.
- Trigger Path: Enter the internal endpoint of the Function Compute HTTP function.
- ContentType: Select Pass-through Client Content-type Header.
- Publish the API. Click Publish in the Actions column of the created API, select the online environment, and then click Publish.
- Create a plug-in whose type is Backend Service Signature. Configure
key
andvalue
as theAccessKey ID
andAccessKey secret
of your Alibaba Cloud account. Then bind the API that you created. For more information, see Overview.
FAQ
Why am I unable to execute an HTTP function?
- For a new trigger, the cache requires approximately 10 seconds to update. You can try again later.
- Check whether the handler that you specified for your function is valid. The handler for an HTTP function is different from the handler for a regular function. For more information about HTTP functions in different languages, see the following topics:
Why am I unable to terminate the execution of a function?
- For a Node.js runtime, you must invoke the
response.send()
function. - For a Python runtime, you must invoke the
return
function. - For a PHP runtime, you must invoke the
return new Response()
function. - For a Java runtime, you must invoke the
HttpServletResponse
function. - For a C# runtime, you must invoke the
return
function. - For a custom runtime, you must invoke the function that is used to send responses based on the programming language.
Troubleshooting
- Request error: A request error occurs when a request does not meet specific requirements. If a request error occurs, an HTTP status code 4xx is returned in the response.
- Function error: A function error occurs when the function code is invalid. In this case, an HTTP status code 5xx is returned.
Error type | X-Fc-Error-Type | The HTTP status code. | Cause | Billable |
---|---|---|---|---|
Request error | FcCommonError | 400 | Your request exceeds the limits on requests. For more information, see Limits. | No |
FcCommonError | 400 | The request for a function that requires identity authentication does not contain date or authorization information. | No | |
FcCommonError | 403 | The signature of the request for a function that requires identity authentication is invalid. As a result, the authorization information is invalid. Date is used to calculate a signature, and the signature is valid only for 15 minutes. If you use an HTTP trigger that requires access authentication, but the date information in the request header is 15 minutes beyond the current time. The signature becomes invalid, and this error occurs. | No | |
FcCommonError | 403 | Your request is sent by using a method that is not configured in the HTTP trigger. For example, if you send an HTTP request by using the POST method, but the GET method, instead of the POST method, is configured in the HTTP trigger, this error occurs. | No | |
FcCommonError | 404 | An HTTP request is sent to a function for which no HTTP trigger is configured. | No | |
User throttling | FcCommonError | 429 | Your traffic is throttled. You can reduce the number of concurrent requests or contact the Function Compute team to increase your concurrency. | No |
Function error | UnhandledInvocationError | 502 | The response of a function exceeds the limits on HTTP responses. For more information, see Limits. | Yes |
UnhandledInvocationError | 502 | The code of a function has a syntax error or exception. | Yes | |
UnhandledInvocationError | 502 | An HTTP request is sent to a function that does not use an HTTP handler function. | Yes | |
A system error occurs. | FcCommonError | 500 | The Function Compute system is abnormal. Try again. | No |
System traffic throttling | FcCommonError | 503 | The Function Compute system traffic is throttled. You can try again in exponential backoff mode. | No |
If the issue persists, Join the DingTalk group 11721331 to communicate instantly with Function Compute engineers..
References
- Use Serverless Devs to configure triggers. For more information, see Serverless Devs.
- Use SDKs to configure triggers. For more information, see SDKs.
To modify or delete an existing trigger, see Trigger management.