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 service

Background 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

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
  2. In the top navigation bar, select a region. On the Services page, click the desired service.
  3. On the Functions page, click Create Function.
  4. 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.
    ParameterDescription
    Basic Settings
    Function NameSpecify the name of the function.
    Request TypeSelect HTTP Requests.
    Trigger Configurations (optional)
    NameSpecify the name of the trigger.
    Disable Internet URLBy 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.
    AuthenticationBy 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 MethodSpecify 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.

On the function details page, click the Code tab, edit the function code in the code editor, and then click Deploy.
Sample code:
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"
    );
}
Important For asynchronous invocations, configure result callbacks for asynchronous invocations in function traces. For more information, see Result callback.

Step 3: Test the function

Method 1: Test the function in the Function Compute console

On the Function Details page, click the Code tab.
  • Synchronous invocation

    Click Test Function on the Code tab.

  • Asynchronous invocation

    Click the down icon next to Test Function, select Asynchronous Invocation, and then click Test Function.

After the test is complete, go to the Code tab and view the test result.

Method 2: Test the function in a browser

Enter the URL of the HTTP trigger in the address bar of a browser. Press the Enter key to execute the function.
After the trigger is executed, the browser returns the execution result.

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 the subdomain assigned by Function Compute to the new HTTP trigger in Function Compute. This helps prevent the 404 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 the 404 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.

    ParameterDescription
    account_idThe 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_idThe region where the Function Compute service resides.
    version The version of the Function Compute API.
    serviceNameThe name of the service.
    functionNameThe name of the function.
    action The custom request path.
    queriesThe query parameter.

Method 3: Use cURL to test the function

  • Synchronous invocation
    Run the following command. After the command is executed, the result is returned.
    curl -v https://http-***.cn-shenzhen.fcapp.run/$path
  • Asynchronous invocation
    Run 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.

  1. 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.
  2. Log on to the API Gateway console and switch to the region where the HTTP function resides.
  3. Create a group. For more information, see Create a group.
  4. 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.
  5. 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.
  6. Publish the API. Click Publish in the Actions column of the created API, select the online environment, and then click Publish.
  7. Create a plug-in whose type is Backend Service Signature. Configure key and value as the AccessKey ID and AccessKey secret of your Alibaba Cloud account. Then bind the API that you created. For more information, see Overview.
After you complete the preceding steps, you can access the HTTP function by using your own domain name. You can also create the following plug-ins and bind them to your API to protect your HTTP functions.

FAQ

Why am I unable to execute an HTTP function?

Why am I unable to terminate the execution of a function?

Check whether the function that is used to send responses is invoked.
  • 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

The following errors may occur when you send requests to invoke functions.
  • 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.
The following table describes the scenarios in which request errors and function errors may occur.
Error typeX-Fc-Error-TypeThe HTTP status code.CauseBillable
Request errorFcCommonError400Your request exceeds the limits on requests. For more information, see Limits. No
FcCommonError400The request for a function that requires identity authentication does not contain date or authorization information. No
FcCommonError403The 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
FcCommonError403Your 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
FcCommonError404An HTTP request is sent to a function for which no HTTP trigger is configured. No
User throttlingFcCommonError429Your traffic is throttled. You can reduce the number of concurrent requests or contact the Function Compute team to increase your concurrency. No
Function errorUnhandledInvocationError502The response of a function exceeds the limits on HTTP responses. For more information, see Limits. Yes
UnhandledInvocationError502The code of a function has a syntax error or exception. Yes
UnhandledInvocationError502An HTTP request is sent to a function that does not use an HTTP handler function. Yes
A system error occurs.FcCommonError500The Function Compute system is abnormal. Try again. No
System traffic throttlingFcCommonError503The 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

In addition to the Function Compute console, you can configure triggers by using the following methods:
  • 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.