All Products
Search
Document Center

Function Compute:Configure and use an HTTP trigger

更新時間:Feb 20, 2024

Function Compute supports HTTP triggers. You can use an HTTP request to invoke a function that is configured with an HTTP trigger. 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 for a function and invoke the function by using HTTP requests in the Function Compute console.

Prerequisites

A service is created. For more information, see Create a service.

Step 1: Create a trigger

Note

An HTTP trigger is different from 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 manually create triggers based on the trigger sources.

  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 parameters to create a function based on your business requirements.

    The following table describes the parameters that you must configure. Retain default values for other parameters. For more information, see Create a function.

    Parameter

    Description

    Basic Settings

    Function Name

    Specify the name of the function.

    Handler Type

    Select HTTP Handler.

    (Optional) Trigger Configurations

    Name

    Specify the name of the trigger.

    Request Method

    Specify HTTP methods that can be used to trigger 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 default public domain name is available for the trigger. In this case, the access denied due to function internet URL is disable error message is returned if you use a public domain name to invoke the function. However, if you use a custom domain name, the function can be invoked as expected.

    Authentication Method

    The method that is used to authenticate HTTP requests. Valid values:

    • No Authentication: Function Compute does not authenticate HTTP requests and supports anonymous access to the function. All users can invoke the function by using HTTP requests.

    • Signature Authentication: Identity authentication is required for HTTP requests. For more information about the sample code for signature authentication, see Signature authentication.

    • JWT Authentication: HTTP requests must be authenticated by using a JSON Web Token (JWT). For more information, see Configure JWT authentication for an HTTP trigger.

    You can modify the configurations of the created HTTP trigger based on your business requirements. For example, you can modify the following parameters of the trigger: Version or Alias, Request Method, Disable Internet URL, and Authentication Method.

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, enter 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

  • Synchronous invocations

    On the function details page, click the Code tab and click Test Function.

  • Asynchronous invocations

    On the function details page, click the Test Function tab, select I want to make the call asynchronously, and then click Test Function.

Method 2: Test the function by using 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 the HTTP trigger:

  • For a new HTTP trigger, we recommend that you use the subdomain name that is assigned by Function Compute as the URL of the HTTP trigger.

    Subdomain format:

    <subdomain>.<region_id>.fcapp.run/[action?queries] 

    Sample code:

    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. If you use the assigned subdomain as the URL of the HTTP trigger to test the function, it can prevent 404 errors and the coupling of service names of Function Compute in the function code. This can improve the portability of the code. For more information about how to handle 404 errors, 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 code:

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

    Parameter description:

    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 Resource Access Management (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 ID of the region where Function Compute resides.

    version

    The Function Compute API version.

    serviceName

    The service name.

    functionName

    The function name.

    action

    The custom request path.

    queries

    The query parameter.

Method 3: Use cURL to test the function

  • Synchronous invocations

    Run the following command. After the command is executed, the result is returned.

    curl -v https://http-***.cn-shenzhen.fcapp.run/$path
  • Asynchronous invocations

    Run the following command. The command output indicates whether Function Compute receives the asynchronous invocation request. If the 202 status code is returned, the asynchronous invocation request succeeds. If another status code is returned, an error occurs during the asynchronous invocation. For more information about status codes, see the Troubleshooting.

    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. Anyone can send an HTTP request to call an HTTP function. To prevent waste of resources and security risks caused by anonymous access, 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 HTTP function that you want to manage. On the function details page, click the Triggers tab, and then edit the HTTP trigger. In the dialog box that appears, set Authentication to Yes.

  2. Log on to the API Gateway console and switch to the region in which the HTTP function resides.

  3. Create a group. For more information, see the Create an API group section of the "Create an API with a backend service of the HTTP type" topic.

  4. Resolve your domain name to the second-level domain name provided by API Gateway by using Canonical Name (CNAME). For more information, see Add a CNAME record.

  5. Create an API.

    The following items describe how to configure the major 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. In subsequent operations, plug-ins are used for authentication.

    • Request Path: Enter the root directory / and select Match All Subpaths.

    • HTTP Method: Select ANY.

    • Request Mode: Select Pass-through.

    • Backend Service Type: Select Function Compute.

    • Function Type: Select HTTP Function.

    • Trigger Path: Select the internal endpoint of an HTTP function in Function Compute.

    • ContentType: Select Pass-through Client Content-type Header.

  6. Publish the API. Find the API that you created, click Publish in the Actions column, select the online environment, and then click Publish.

  7. Create a plug-in whose type is Backend Signature. Set key and value to the AccessKey ID and AccessKey secret of your Alibaba Cloud account. Then bind the plug-in to 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 function.

Troubleshooting

Why am I unable to execute an HTTP function?

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

You can 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 errors: A request error occurs when the request does not meet specific requirements. In this case, an HTTP status code 4xx is returned in the response.

  • Function errors: 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 errors

FcCommonError

400

Your request exceeds the limits on requests. For more information, see Overview.

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, which indicates that the authorization information is invalid. Date is used to calculate a signature, and the signature is valid only for 15 minutes. When you use the HTTP trigger that requires access authentication, the signature becomes invalid if the date information in the request header has been generated for 15 minutes.

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 traffic throttling

FcCommonError

429

Your traffic is throttled. You can reduce concurrent requests or contact the Function Compute team to increase your concurrency.

No

Function errors

UnhandledInvocationError

502

The response of a function exceeds the limits on HTTP responses. For more information, see Overview.

Yes

UnhandledInvocationError

502

The code of a function contains a syntax error or an exception.

Yes

UnhandledInvocationError

502

An HTTP request is sent to a function that does not use an HTTP handler.

Yes

A system error occurs.

FcCommonError

500

A system error occurs in Function Compute. Try again.

No

System traffic throttling

FcCommonError

503

System throttling is enabled for Function Compute. You can try again in exponential backoff mode.

No

If the issue persists, join the DingTalk user group (ID: 11721331) and contact Function Compute technical support.

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

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