Function Compute supports HTTP triggers. Functions that configure HTTP triggers can be triggered through HTTP requests. In this case, the function can be considered like a web server, which receives HTTP requests and returns the processed results to the caller. This topic describes how to configure an HTTP trigger in the Function Compute console.

Prerequisites

Create a service

Background information

Creating an HTTP trigger is different from creating other types of triggers. The HTTP trigger-related parameters are configured when you create the function. However, parameters of other types of triggers are configured in the created function.

Procedure

  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 service that you want to manage 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. In the Basic Settings section, enter the function information and click Create.
    create-function
    Parameter Configuration method Example
    Parameter The name of the function. http-function
    Runtime environment Select a language that is familiar to you, such as Python, Java, PHP, or Node.js. Python3
    Function trigger mode Select Triggered by Event or Triggered by HTTP Request. Triggered by HTTP request
    Instance architecture Select Elastic Instance or Performance Instance. Elastic instance
    Memory specification The memory that is required to execute the function. Valid values:
    • Select Elastic Instance. The memory specifications can be 128 MB, 256 MB, 512 MB, 1 GB, 2 GB, or 3 GB.
    • Select Performance Instance. The memory specification can be 4 GB, 8 GB, 16 GB, or 32 GB.
    512 MB
    After the function is created, a default HTTP trigger is automatically created. Click the target function, and then click the Triggers tab. You can view the HTTP triggers created by default. http-trigger

Write code for a function

After you create an HTTP trigger, you can start writing function code.

On the function details page, click the Function Code tab and write code in the code editor.
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"
    );
}

Debug a function

You can use the Function Compute console or a browser to send HTTP requests to test whether the function is correct.

Use the console to test functions
On the function details page, click the Function Code tab, and then click Test Function.
After the execution is complete, you can view the message that appears on the Function Code tab. http-function-result
Use a browser to test functions
  1. Assemble the HTTP trigger URL.
    The assembly rules of the HTTP trigger URL are as follows:
    <account_id>.<region>.fc.aliyuncs.com/<version>/proxy/<serviceName>/<functionName>/[action?queries]            

    Example:

    123456.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/serviceName/functionName/action?hello=world           
    The parameters in URL are described as follows:
    Parameter Description
    account_id The ID of your Alibaba Cloud account.

    You can retrieve your account ID in Security Settings If you are a RAM user, move the pointer over the avatar in the upper-right corner of the console to view your Alibaba Cloud account ID.

    region The region where the Function Compute instance is located.
    version The API version of Function Compute.
    serviceName The name of the service.
    functionName The name of the function.
    action The custom request path.
    queries The query parameter.
  2. In the address bar of your browser, enter the HTTP trigger URL and press Enter.
    The browser returns the execution result.

FAQ

Why is the HTTP function unable to be executed?

Why does the function fail to end?

Check whether a function for sending a response is invoked.
  • For a Node.js HTTP function, you must invoke response.send().
  • For a Python HTTP function, you must invoke return.
  • For a PHP HTTP function, you must invoke return new Response().
  • For a Java HTTP function, you must invoke HttpServletResponse.
  • For a C# HTTP function, you must invoke return.
  • For an HTTP function in a custom runtime, you must invoke a function for sending a response based on the corresponding language.

Troubleshooting

You may encounter the following two types of errors:
  • Request errors: A request error occurs if a request does not meet specific requirements. In this case, a status code 4xx is returned in the response.
  • Function errors: A function error occurs if the function code is invalid. In this case, a status code 5xx is returned.
The following table describes the scenarios where request and function errors may occur.
Error type X-Fc-Error-Type The HTTP status code. Description Billable
Request error FcCommonError 400 The error returned because your request exceeds the limits on HTTP requests. For more information, see Limits. No
FcCommonError 400 The error returned because the request for a function that requires authentication does not contain date or authorization information. No
FcCommonError 403 The error returned because the signature of a request for a function that requires authentication is invalid, that is, the authorization information is invalid. The date information is used in signature calculation and a signature is only valid for 15 minutes. A common cause is that you use an HTTP trigger that requires access authentication, but the date information in the request header is more than 15 minutes from the current time. In this case, the signature becomes invalid. No
FcCommonError 403 The error returned because your request uses a request method that is not configured in the HTTP trigger. For example, you only configure the GET method in an HTTP trigger but send an HTTP request that uses the POST method. No
FcCommonError 404 The error returned because you send an HTTP request to a function for which no HTTP trigger is configured. No
User throttling FcCommonError 429 The error returned because your traffic is throttled. You can reduce concurrent requests or contact the Alibaba Cloud Function Compute team to increase your concurrency. No
Function errors UnhandledInvocationError 502 The error returned because the response of a function exceeds the limits on HTTP responses. For more information, see Limits. Yes
UnhandledInvocationError 502 The error returned because the code of a function has a syntax error or exception. Yes
UnhandledInvocationError 502 The error returned because an HTTP request is sent to a function that does not use an HTTP handler function. Yes
The error message returned because a system error has occurred. FcCommonError 500 The error returned because the Function Compute system is abnormal. You can try again. No
System throttling FcCommonError 503 The error returned because throttling is implemented for the Function Compute system. You can try again by using exponential backoff. No

If your problem persists, Contact us.

Additional information

In addition to the Function Compute console, you can configure triggers in the following ways:
  • Use the Serverless Devs tool to configure triggers. For more information, see Serverless Devs.
  • Configure triggers by using the SDK. For more information, see Supported SDKs.

To modify or delete a created trigger, see Manage triggers.