All Products
Search
Document Center

HTTP trigger

Last Updated: Feb 14, 2020

Note:

1. The function interface for setting the HTTP trigger is different from the common function interface. For more information, see HTTP trigger interface form.

HTTP triggers are a common type of triggers used in Function Compute to invoke functions when an HTTP request is sent. With HTTP triggers, you can quickly construct web services. HTTP triggers support HEAD, POST, PUT, GET, and DELETE method triggers.

Compared to API Gateway triggers, which are difficult for new users, HTTP triggers offer the following advantages:

  • The easier learning and debugging processes help you quickly implement web services and APIs by using Function Compute.
  • You can use the HTTP testing tools you are familiar with to verify the functionality and performance of Function Compute.
  • Requests are processed in fewer stages. HTTP triggers support more efficient request and response formats and are not encoded or decoded into JSON strings. Therefore, the performance is improved.
  • You can easily connect to other services that support webhooks, such as Content Delivery Network (CDN) back-to-origin and Message Notification Service (MNS).

Note:

  1. You can bind a custom domain name to map different HTTP access paths to HTTP functions. You can also use API Gateway by selecting the HTTP service as the backend trigger type and configuring an HTTP function as the backend service address for the same purpose.
  2. For security, when you use the default domain name aliyuncs.com of Function Compute, the server inserts the content-disposition: attachment field into the response header. This field is used to download the returned result in the browser as an attachment. To remove this limit, set a custom domain name.

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 for the function.

  • A function can have only one HTTP trigger.

  • Under version control, only one HTTP trigger can be configured for each (version or alias, function) combination.

    • For example, an HTTP trigger can be configured for alias 1 that directs to version 1 (version 1, function 1), and an HTTP trigger can be configured for (alias 1, function 1).
  • Note: The following fields in the Request Headers key are ignored. Function Compute contains these fields by default and does not support custom settings. Keys that start with x-fc- are also ignored.

  • accept-encoding

  • connection

  • keep-alive

  • proxy-authorization

  • te

  • trailer

  • transfer-encoding

  • Note: The following fields in the Response Headers key are ignored. Function Compute contains these fields by default and does not support custom settings. Keys that start with x-fc- are also ignored.

  • connection

  • content-length

  • content-encoding

  • date

  • keep-alive

  • proxy-authenticate

  • server

  • trailer

  • transfer-encoding

  • upgrade

  • content-disposition: attachment (This field is added after the custom domain name is set.)

Request limits

If the following limits are exceeded, the system throws a 400 status code and InvalidArgument error code.

  • Header size:The total size of all keys and values in the headers cannot exceed 4 KB.
  • Path size:The path size, including all parameters, cannot exceed 4 KB.
  • Body size:The size of the HTTP response body cannot exceed 6 MB.

Response limits

If the following limits are exceeded, the system throws a 502 status code and BadResponse error code.

  • Header size:The total size of all keys and values in the headers cannot exceed 4 KB.
  • Body size:The size of the HTTP response body cannot exceed 6 MB.

HTTP trigger interface format

The function interface for setting the HTTP trigger is different from that of Function Compute. Currently, Node.js runtime, Python runtime, PHP runtime, and Java runtime are supported.

For more information about the interface format, see:

The following figure shows common functions (left) and functions with HTTP triggers (right). If you are still using common interfaces after setting HTTP triggers, correct this promptly.

Node.js:

nodejs_comparePython:

python_compare

Configure an HTTP trigger

Assemble the HTTP trigger URL

You can send an HTTP request to the following URL to invoke the function:

  1. // A common HTTP trigger URL
  2. <account_id>.<region>.fc.aliyuncs.com/<version>/proxy/<serviceName>/<functionName>/[action?queries]
  3. // The HTTP trigger URL under version control
  4. <account_id>.<region>.fc.aliyuncs.com/<version>/proxy/<serviceName>.<qualifier>/<functionName>/[action?queries]
  • “version” specifies the version of the Function Compute API. For more information, see version.
  • “serviceName” specifies the trigger-directed service. “qualifier” specifies the version or alias of the trigger-directed service. The connector is period (.). For more information, see Version control. When “version” is set, the URL does not specify a “qualifier”, and the request is processed by the latest version.
  • “queries” is the query parameter of the HTTP request.

Example:

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

HTTP trigger configuration

HTTP trigger configuration format:

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

The HTTP trigger configuration has two key fields:

  • authType: the authentication type with these values:

    • anonymous: The server does not require identity authentication and supports anonymous access. The system is of low security.
      Example:

      1. curl "<account-id>.<region>.fc.aliyuncs.com/2016-08-15/proxy/serviceName/functionName/action?hello=world"
    • function: The server requires identity authentication and does not support anonymous access. The system is highly secure. Requests must pass signature authentication and HTTP request headers must contain Authorization and Date. The Date parameter is in UTC format and is used to calculate the signature. The server uses the Date value to calculate the signature and compares it with the transmitted Authorization value. The request passes the authentication only if the signatures match and the difference between the current time and the Date value is less than 15 minutes.

  • methods: The access methods supported by the HTTP trigger:
    • HEAD: HTTP HEAD method
    • GET: HTTP GET method
    • POST: HTTP POST method
    • PUT: HTTP PUT method
    • DELETE: HTTP DELETE method

Example 1 Console operation

This example shows how to create an HTTP trigger in the console.

For information about triggers and how to create them, see Introduction to triggers and Create a trigger.

Step 1 Configure an HTTP trigger

You can select and configure a trigger when or after creating a function.

Configure a trigger when creating a function

  1. Log on to the Function Compute console.

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

  3. Select a service and function in the left-side navigation pane.

  4. Click Create Function.

  5. On the Create Function page, click HTTP Function.
  6. Create a function and set Service Name, Function Name, Function Description, and Runtime. Configure an HTTP trigger according to the following figure, and then click OK.
    1

  7. On the Code Execution page, select In-line Edit and paste the following Node.js runtime sample code for the HTTP function.

  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. };
  1. Click Save.

Step 2 Debug the trigger

  1. Select the target function. On the page that appears, click the Code tab and scroll down the page.

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

    params

  3. Click the Header tab to set the request header and enter your key-value pairs. When authentication is required, the request header on this tab automatically contains the Date and Authorization keys.headers

  4. Click Invoke.

Fun supports HTTP triggers and allows you to create and update function triggers. The following steps show how to use Fun to configure an HTTP trigger.

First, create an index.js file in the root directory of your project.

  1. var getRawBody = require('raw-body')
  2. module.exports.handler = function (request, response, context) {
  3. // get request body
  4. getRawBody(request, function (err, body) {
  5. var respBody = {
  6. headers: request.headers,
  7. url: request.url,
  8. path: request.path,
  9. queries: request.queries,
  10. method: request.method,
  11. clientIP: request.clientIP,
  12. body: body.toString()
  13. };
  14. response.setStatusCode(200);
  15. response.setHeader('content-type', 'application/json');
  16. response.send(JSON.stringify(respBody, null, 4));
  17. });
  18. };

Configure related services. Create a template.yml file in the root directory of your project:

  1. ROSTemplateFormatVersion: '2015-09-01'
  2. Transform: 'Aliyun::Serverless-2018-04-03'
  3. Resources:
  4. FunDemo:
  5. Type: 'Aliyun::Serverless::Service'
  6. httpdemo:
  7. Type: 'Aliyun::Serverless::Function'
  8. Properties:
  9. Handler: index.handler
  10. CodeUri: . /
  11. Description: 'http trigger demo!'
  12. Runtime: nodejs8
  13. Events:
  14. http-test:
  15. Type: HTTP
  16. Properties:
  17. AuthType: ANONYMOUS
  18. Methods: ['GET', 'POST', 'PUT']

After compiling the code and template file, run the fun deploy command to deploy services online with one click.

  1. $ fun deploy
  2. using region: cn-hangzhou
  3. using accountId: ***********3557
  4. using accessKeyId: ***********r3Ra
  5. using timeout: 300
  6. Waiting for service FunDemo to be deployed...
  7. Waiting for function httpdemo to be deployed...
  8. Waiting for packaging function httpdemo code...
  9. package function httpdemo code done
  10. Waiting for HTTP trigger http-test to be deployed...
  11. methods: [ 'GET', 'POST', 'PUT' ]
  12. url: https://1911504709953557.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/FunDemo/httpdemo/
  13. function httpdemo deploy success
  14. function FunDemo deploy success
  15. service FunDemo deploy success

Open a browser, and enter the address https://1911504709953557.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/FunDemo/httpdemo/ to trigger the function execution. For HTTP triggers, the server inserts the content-disposition: attachment field into the response header. This field is used to open the returned result in the browser as an attachment. This field cannot be overridden and is immune to the use of a custom domain name. For more information, see Function Compute FAQ.

If the HTTP trigger configuration is modified, run the fun deploy command again.

To step through and run functions with HTTP triggers locally, see Guidelines for Function Compute Development - Local Running and Debugging of HTTP Triggers.

For more configuration rules, see here.

For more Fun tutorials, click here.

Example 3 Create an HTTP trigger through SDK programming

The following example shows how to use the Python SDK to create an HTTP trigger.

Note: The functions that use interfaces with HTTP triggers can be invoked only by sending HTTP requests to specified addresses, but not by using the invoke_function method in SDKs.

Prerequisites

  • You have deployed the Python environment.
  • You have installed the Python SDK for Function Compute. pip install aliyun-fc2 To obtain the Python SDK for Function Compute, run pip install aliyun-fc2 on your local device.

Procedure

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

  2. Create the file create_http_trigger.py, create_http_trigger.py and copy and paste the following Python code 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. Run python create_http_trigger.py python create_http_trigger.py to create an HTTP trigger.

  2. Send an HTTP request to invoke 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

Example 3: Initializer interface

When using an HTTP trigger, you can also apply the initialization logic to the initializer function. When the initializer function and HTTP trigger are used in combination, they can maintain their original structures without any special changes. For more information about the initializer interface, see the initializer entry definition.

The Python runtime sample code is as follows:

  1. # -*- coding: utf-8 -*-
  2. import logging
  3. HELLO_WORLD = b"Hello world!\n"
  4. def initializer(context):
  5. logger = logging.getLogger()
  6. logger.info("initialized")
  7. def handler(environ, start_response):
  8. logger = logging.getLogger()
  9. logger.info("run after initialized")
  10. context = environ['fc.context']
  11. request_uri = environ['fc.request_uri']
  12. for k, v in environ.items():
  13. if k.startswith("HTTP_"):
  14. # process custom request headers
  15. pass
  16. # do something here
  17. status = '200 OK'
  18. response_headers = [('Content-type', 'text/plain')]
  19. start_response(status, response_headers)
  20. return [HELLO_WORLD]

Example 4 Create an HTTP trigger by using fcli

The following example shows how to create an HTTP trigger in the Node.js 6 runtime by using the command-line tool fcli:

  • Create the http_echo and http_echo/code directories.
  • Paste the code in http_echo/code/index.js and create config.json.
  1. {
  2. "triggerConfig": {
  3. "authType" : "anonymous",
  4. "methods" : ["GET", "POST"]
  5. }
  6. }
  • Run the following command to create the test_echo function in the test_service service:
  1. fcli function create -s test_service -f test_echo --runtime nodejs6 --code-dir code --handler index.handler
  • Run the following command to retrieve all trigger information about the test_echo function:
  1. fcli trigger list -s test_service -f test_echo
  • Run the following command to create an HTTP trigger named test_trigger_name in the test_echo function of the test_service service:
  1. fcli trigger create -s test_service -f test_echo --trigger-name test_trigger_name --type http --source-arn dummy --config config.json
  • Run the following command to update information about the test_trigger_name trigger for test_echo:
  1. fcli trigger update -s test_service -f test_echo -t test_trigger_name --trigger-config config.json
  • Run the following command to delete the test_trigger_name trigger from test_echo:
  1. fcli trigger delete -s test_service -f test_echo -t test_trigger_name
  • For more information, watch this video (commands can be copied):

Troubleshooting

The main types of errors are request errors and function errors. A request error occurs when the request sent by the user does not comply with the standard and the response contains a 4xx status code. A function error occurs when the function is improperly programmed and a 5xx status code is returned. Scenarios in which request and function errors may occur are described in the following table to facilitate your quick troubleshooting.

Error types X-Fc-Error-Type HTTP status code Cause analysis Charged
Request error FcCommonError 400 The request exceeds the limits on responses. No
FcCommonError 400 A request to invoke a function that requires identity authentication does not contain Date or Authorization. No
FcCommonError 403 The signature of a request to invoke a function that requires identity authentication is incorrect, that is, the Authorization is incorrect. A common cause is that the HTTP trigger requires identity authentication while the signature is invalid because the difference between the Date used to calculate the signature and the current time is more than 15 minutes. No
FcCommonError 403 The method in the request is not configured in the HTTP trigger. For example, only the GET method is configured in the HTTP trigger while the POST method is requested. No
FcCommonError 404 An HTTP request is sent to invoke a function without any HTTP trigger. No
User throttling FcCommonError 429 The user has been throttled. You can reduce the concurrent request volume or contact the Alibaba Cloud Function Compute team to increase your concurrency. No
Function errors UnhandledInvocationError 502 The value returned by the function exceeds the limits on responses. Yes
UnhandledInvocationError 502 The function code has a syntax error or exception. Yes
UnhandledInvocationError 502 An HTTP request is sent to a function that does not use an HTTP interface. Yes
A system error occurred while processing your request. FcCommonError 500 Function Compute system error. Please try again. No
System throttling FcCommonError 503 Function Compute has activated system throttling. Implement exponential backoff retry attempts. No

If the problem persists, please contact us.