All Products
Search
Document Center

HTTP trigger

Last Updated: May 30, 2019

HTTP triggers are a type of trigger used in Function Compute to send an HTTP request to trigger a function execution. With HTTP triggers, you can construct web services. HTTP triggers support the HEAD, POST, PUT, GET, and DELETE methods to trigger functions.

Note:

  1. Handlers with an HTTP trigger are different from common handlers. For more information, see Comparison between a common handler and one with an HTTP trigger.
  2. Currently, the Java runtime environment does not support HTTP triggers. Please join our dingtalk group for the latest news.

Benefits

Compared with triggers of API Gateways, HTTP triggers have the following advantages:

  • Easy to manage and debug. HTTP triggers help you quickly implement web services and APIs using Function Compute.
  • Allows you to test the functionality and performance of the Function Compute host using standard HTTP testing tools.
  • Simplifies request processing. HTTP triggers can process requests and responses in different formats. This saves the process of encoding or decoding them into JSON strings, ensuring higher efficiency.
  • Connects to services that support WebHook callbacks more easily, such as CDN origin-fetch and MNS.

Contents

This topic describes the following aspects of HTTP triggers:

Limits

  • Once an HTTP trigger is set for a function, the trigger type cannot be changed.
  • A function must have only one HTTP trigger.

Limits on requests

If a request meets the following restrictions, a 400 status code and an InvalidArgument error code are displayed.

  • Size of headers: The size of all keys and values of the headers parameter cannot exceed 4 KB.
  • Size of path: The size of path equals the size of all query parameters, and it cannot exceed 4 KB.
  • Size of body: The size of the HTTP request body cannot exceed 6 MB.

Limits on responses

If a response meets the following restrictions, a 502 status code and a BadResponse error code are displayed.

  • Size of headers: The size of all keys and values of the headers parameter cannot exceed 4 KB.
  • Size of body: The size of the HTTP response body cannot exceed 6 MB.

Configure HTTP trigger

Construct a URL

You can send an HTTP request to the following address to call a function:

  1. <account_id>.<region>.fc.aliyuncs.com/<version>/proxy/<serviceName>/<functionName>/[action?queries]

In the URL, action, queries, request header, body, and other information are included in the request parameter of the function handler in Function Compute.

HTTP trigger Config

You can set the HTTP trigger Config to the following format:

  1. {
  2. "authType" : "anonymous",
  3. "methods" : ["GET", "POST"]
  4. }

Generally, Config uses two fields: authType and methods, which are described as follows:

  • authType: indicates the authentication type. It can be set to anonymous or function, as follows:
    • anonymous: indicates that the server does not require authentication and supports anonymous access. A system in this mode is moderately secure.
      Example:
      1. curl "<account-id>.<region>.fc.aliyuncs.com/2016-08-15/proxy/serviceName/functionName/action?hello=world"
    • function: indicates that the server requires authentication and does not support anonymous access. A system in this mode is highly secure. Additionally, Signature authentication must be passed. You must add Authorization and Date information to the header of the HTTP request. Date is in GMT format and is involved in the signature algorithm. The server calculates the signature based on Date and compares the result with the input value of Authorization. Authentication passes only when the comparison result meets the requirements, and the difference between the current time and the Date value is within 15 minutes.
  • methods: indicates the access method supported by the HTTP trigger. The following methods can be used:
    • HEAD: HTTP HEAD
    • GET: HTTP GET
    • POST: HTTP POST
    • PUT: HTTP PUT
    • DELETE: HTTP DELETE

Handlers with an HTTP trigger

Handlers with an HTTP trigger are different from common handlers in Function Compute. Currently, Function Compute supports Node.js and Python runtime environments. For more information about the types of handlers, see the following related topics:

The following figures compare common handlers (on the left) with handlers that have an HTTP trigger (on the right) in Node.js and Python runtime environments. After you have configured an HTTP trigger, you can only use handlers that support the HTTP trigger.

Node.js runtime environment:

nodejs_compare

Python runtime environment:

python_compare

Example 1: Operations in the console

The following example describes how to use the Function Compute console to set HTTP triggers. For more information about triggers and how to create them, see Introduction and Create a trigger.

Step 1: Configure an HTTP trigger.

You can create a trigger when creating a function, or after the function is created.

Create a trigger when creating a function

  1. Log on to the Function Compute console.

  2. Select a region, such as China (Shanghai).

  3. In the left-side navigation pane, select a service.

  4. Click Create Function. On the displayed page, follow these steps:

    a. Click Select All and select Node.js8 from the drop-down list. b. Select the Empty Function template. c. (Optional) Select HTTP Trigger and configure the parameters as needed. Then, click Next. You can also select No Trigger.
    Create a trigger d. Create a function and set Service Name, Function Name, Function Description, and Runtime. e. In the Code Configuration area, select In-line Edit and paste the following sample code for the handler with an HTTP trigger. Note that this example is run in the Node.js runtime environment:

    1. var getRawBody = require('raw-body')
    2. module.exports.handler = function (request, response, context) {
    3. // get requset header
    4. var reqHeader = request.headers
    5. var headerStr = ' '
    6. for (var key in reqHeader) {
    7. headerStr += key + ':' + reqHeader[key] + ' '
    8. };
    9. // get request info
    10. var url = request.url
    11. var path = request.path
    12. var queries = request.queries
    13. var queryStr = ''
    14. for (var param in queries) {
    15. queryStr += param + "=" + queries[param] + ' '
    16. };
    17. var method = request.method
    18. var clientIP = request.clientIP
    19. // get request body
    20. getRawBody(request, function (err, data) {
    21. var body = data
    22. // you can deal with your own logic here
    23. // set response
    24. // var respBody = new Buffer('requestURI' + requestURI + ' path' + path + ' method' + method + ' clientIP' + clientIP)
    25. var respBody = new Buffer('requestHeader:' + headerStr + '\n' + 'url: ' + url + '\n' + 'path: ' + path + '\n' + 'queries: ' + queryStr + '\n' + 'method: ' + method + '\n' + 'clientIP: ' + clientIP + '\n' + 'body: ' + body + '\n')
    26. // var respBody = new Buffer( )
    27. response.setStatusCode(200)
    28. response.setHeader('content-type', 'application/json')
    29. response.send(respBody)
    30. })
    31. };

    f. Click Next. j. (Optional) Configure the required permissions. h. Confirm the settings and click Create.

Create a trigger after creating a function

  1. Log on to the Function Compute console.

  2. Select a region, such as China (Shanghai).

  3. In the left-side navigation pane, select a service.

  4. Select a function.

  5. Click the Trigger tab, and then click Create Trigger.

  6. On the displayed page, select HTTP Trigger and set the parameters as needed. Then, click OK.

    Create a trigger

Step 2: Debug the trigger.

  1. Select a function. On the displayed page, click the Code tab and scroll down the page until the Params tab is displayed.

  2. Click the Params tab and enter the key-value pairs. The key-value pairs are automatically added to the HTTP URL.

    params

  3. Click the Header tab and enter the key-value pairs for the request header. When authentication is needed, the request header on this tab automatically contains the Date and Authorization keys.

    headers

  4. Click Invoke.

Example 2: SDK programming

This example uses the Python SDK to create an HTTP trigger.

Note: You can call a function with an HTTP trigger only by sending an HTTP request to the designated address. The invoke_function method in SDK programming cannot be used.

Prerequisites

  • You have deployed a Python runtime environment.
  • You have installed the Function Compute Python SDK tool. You can run the pip install aliyun-fc2 command on your local device to obtain the tool.

Procedure

  1. Compile a function in Function Compute, and copy and paste the sample code to the main.js file in the code folder.

  2. Create a file named create_http_trigger.py, and copy and paste the following Python commands to the file:

  1. import fc2
  2. import os
  3. def main():
  4. service_name = "http_trigger_service"
  5. func_name = "test_http_trigger_node"
  6. endpoint = os.getenv("FC_ENDPOINT")
  7. url = "%s/2016-08-15/proxy/%s/%s" % (endpoint, service_name, func_name)
  8. print url
  9. fc_client = fc2.Client(
  10. endpoint=endpoint,
  11. accessKeyID=os.getenv("ACCESS_KEY_ID"),
  12. accessKeySecret=os.getenv("ACCESS_KEY_SECRET"),
  13. Timeout=5)
  14. fc_client.create_service(service_name)
  15. fc_client.create_function(service_name, func_name, "nodejs6", "main.handler", codeDir='./code')
  16. trigger_config = {
  17. "authType" : "anonymous",
  18. "methods" : ["GET", "POST"],
  19. }
  20. fc_client.create_trigger(service_name, func_name, "trigger_on_echo", "http", trigger_config, "dummy_arn", "")
  21. main()
  1. Enter the python create_http_trigger.py command to create an HTTP trigger.

  2. Send an HTTP request to call the function.

    Example:

    1. curl -v "<account-id>.<region>.fc.aliyuncs.com/2016-08-15/proxy/http_trigger_service/test_http_trigger_node/action"

The result is as follows:

Result

Troubleshooting

After you create an HTTP trigger and call a function, request errors and function errors may occur. A request error occurs when your request is invalid, and the response parameter contains a 4xx status code. A function error occurs when the function is improperly programmed and a 5xx status code is returned. The following table describes the scenarios in which request errors or function errors may occur, and how to quickly troubleshoot such errors.

Error type X-Fc-Error-Type HTTP status code Description Still billed?
Request errors FcCommonError 400 The request exceeds the limit for responses. No
FcCommonError 400 The request for calling the function that requires authentication does not contain Date or Authorization. No
FcCommonError 403 The signature of a request for calling a function that requires authentication is incorrect. A common cause is that the HTTP trigger requires authentication. However, the signature is invalid because the difference between the Date value and the current time exceeds 15 minutes. No
FcCommonError 403 The method used in the request is not configured in the HTTP trigger. For example, only the GET method is configured in the HTTP trigger, but the POST method is requested. No
FcCommonError 404 An HTTP request is sent to call a function without any HTTP trigger. No
User throttling errors FcCommonError 429 Throttling is performed on your traffic to reduce concurrencies. You can submit a ticket and request an increase to your concurrency quota. No
Function errors UnhandledInvocationError 502 The value that the function returns exceeds the limit for responses. Yes
UnhandledInvocationError 502 The function code has a syntax error or an exception. Yes
UnhandledInvocationError 502 An HTTP request is sent to a function that does not have an HTTP trigger. Yes
System errors FcCommonError 500 You can resolve system errors that occur in Function Compute by re-initiating a request. No
System throttling errors FcCommonError 503 You can resolve system throttling errors by resubmitting exponential backoff retry attempts. No

If the errors persist, contact us.