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 in the Function Compute console and use the HTTP trigger.

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, the system automatically creates an HTTP trigger for the function. For other types of triggers, you must create the triggers based on the trigger source in a function that is triggered by events.

Step 1: Create a trigger

  1. Log on to the Function Compute console.
  2. In the left-side navigation pane, click Services and Functions.
  3. In the top navigation bar, select the region where the service resides.
  4. On the Services page, find the desired service and click Functions in the Actions column.
  5. On the Functions page, click Create Function.
  6. On the Create Function page, select Create from Scratch with a Standard Runtime. In the Basic Settings section, configure the information about the function.
    Select HTTP Requests for Request Type. For more information about the configurations of other parameters, see Create a function.
  7. Optional:In the Trigger Configurations section of the Create Function page, enter a trigger name, configure the Authentication and Request Method parameters, and then click Create.
    If you do not configure the trigger, the system creates an HTTP trigger for the function. Click the name of the function. On the function details page that appears, click the Triggers tab. The created HTTP trigger appears in the trigger list.

    You can modify settings of the HTTP trigger based on your business requirements, including the Authentication and Request Method parameters. For more information, see Update the configurations of a trigger.

Step 2: Write and deploy code

After the HTTP trigger is created, you can write code for the function.

On the function details page, click the Code tab, enter function code in the code editor, and then click Save.
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"
    );
}
Notice 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 trigger.
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] 

    Sample URL:

    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. However, 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]            

    Sample URL:

    164901546557****.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/serviceName/functionName/action?hello=world           

    The following table describes the parameters in the assembly rule.

    Parameter Description
    account_id The ID of your 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 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.
    Configure main parameters as described in the following items. For other parameters, you can use the default values or specify them 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 end a function?

Check whether a 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 of the corresponding 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 type X-Fc-Error-Type HTTP status code Cause Billable
Request error FcCommonError 400 Your request exceeds the limits on HTTP 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, Contact Us.

Additional information

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 Supported SDKs.

To modify or delete an existing trigger, see Manage triggers.