Web functions

更新时间:
复制 MD 格式

This topic describes the invocation methods, limitations, and code examples for functions in a custom runtime.

Background information

A custom runtime can host your HTTP server. Function Compute converts function invocation requests into HTTP requests and sends them to your HTTP server. Function Compute then converts the responses from your server into function invocation responses and returns them to the client. The following figure shows the process.

image

You can invoke a function in one of the following two ways:

  • Http call (Recommended): Invoke the function over HTTP by using an http trigger or a custom domain name.

  • Api call: Invoke the function by calling the InvokeFunction API, such as by using an SDK or an event source.

The format of HTTP requests and responses depends on the invocation method.

Limits

  • You can create only one http trigger for each function version or alias. For more information, see Manage versions and Manage aliases.

  • HTTP request limits

    • Request headers cannot contain custom fields that start with x-fc- or the following fields:

      • connection

      • keep-alive

    • If a request exceeds the following limits, Function Compute returns a 400 status code and an InvalidArgument error code.

      • Header size: The total size of all keys and values in the headers cannot exceed 8 KB.

      • Path size: The total size of the path, including all query parameters, cannot exceed 4 KB.

      • Body size: The total size of the request body for a synchronous invocation cannot exceed 32 MB. The total size of the request body for an asynchronous invocation cannot exceed 128 KB.

  • HTTP response limits

    • Response headers cannot contain custom fields that start with x-fc- or the following fields:

      • connection

      • content-length

      • date

      • keep-alive

      • server

      • content-disposition:attachment

        Note

        For security reasons, when you use the default aliyuncs.com domain for Function Compute, the server forcefully adds the content-disposition: attachment header to the response. This header causes the response to be downloaded as an attachment in your browser. To remove this restriction, configure a custom domain name.

    • If a response exceeds the following limit, Function Compute returns a 502 status code and a BadResponse error code.

      • Header size: The total size of all keys and values in the headers cannot exceed 8 KB.

  • Additional notes

    You can map different HTTP access paths to your function by binding a custom domain name. For more information, see Configure a custom domain name.

HTTP call (Recommended)

For http calls, Function Compute uses a passthrough mode. It forwards the client's HTTP request to your HTTP server and passes the server's response back to the client. Function Compute does not pass through some system-reserved fields. For more information, see Limits.

Request header

When invoking a function with an http trigger or a custom domain name, use the request headers described below to control the request.

Name

Type

Required

Example

Description

X-Fc-Invocation-Type

String

No

Sync

Specifies the invocation method. For more information, see Invocation methods. Valid values:

  • Sync: synchronous invocation.

  • Async: asynchronous invocation.

X-Fc-Log-Type

String

No

Tail

Specifies whether to return logs in the response. Valid values:

  • Tail: Returns the last 4 KB of logs generated for the request.

  • None: Does not return request logs. This is the default value.

Response header

Function Compute adds the default headers described below to the response.

Name

Description

Example

X-Fc-Request-Id

The unique request ID for the function invocation.

dab25e58-9356-4e3f-97d6-f044c4****

API call

When a function is invoked by using the InvokeFunction API, Function Compute converts the API request into an HTTP request and sends it to your HTTP server. The conversion follows these rules:

  • The event parameter of the InvokeFunction request becomes the message body of the HTTP request.

  • The path is /invoke.

  • The method is POST.

  • The Content-Type request header is application/octet-stream.

Function Compute converts the response from your HTTP server into the InvokeFunction API response and returns it to the client. The conversion follows these rules:

  • The HTTP response body becomes the InvokeFunction response body.

  • This conversion discards the HTTP response headers and status code.

InvokeFunction API request conversion example

Invoke request

HTTP request

Invoke API request content:

"hello world"
> POST /invoke HTTP/1.1
> Host: 21.0.X.X
> Content-Length: 11
> Content-Type: application/octet-stream

hello world

InvokeFunction API response example

HTTP response

Invoke response

< HTTP/1.1 200 OK
< Date: Mon, 10 Jul 2025 10:37:15 GMT
< Content-Type: application/octet-stream
< Content-Length: 11
< Connection: keep-alive

hello world
hello world
< HTTP/1.1 400 Bad Request
< Date: Mon, 10 Jul 2025 10:37:15 GMT
< Content-Type: application/octet-stream
< Content-Length: 28
< Connection: keep-alive

{"errorMessage":"exception"}
{"errorMessage":"exception"}

Function Compute response codes and response headers

A custom runtime is essentially an HTTP server that you implement. Therefore, each function invocation is an HTTP request, and each response includes a status code and response headers.

  • Response status code

    • 200: Success.

    • 404: Failure.

  • Response header x-fc-status

    • 200: Success.

    • 404: Failure.

You can use the x-fc-status response header to report the function's execution status to Function Compute.

  • If you do not set the x-fc-status header, Function Compute assumes the invocation was successful by default. However, if your function encounters an error without reporting it, Function Compute will not recognize the failure. This might not affect your business logic, but it will impact monitoring and observability. The following code shows an example:

        print("FC Invoke Start RequestId: " + rid)
        data = request.stream.read()
        print("Path: " + path)
        print("Data: " + str(data))
        # Simulate an exception to trigger a runtime error
        raise Exception("mock exception")
        print("FC Invoke End RequestId: " + rid)
        return "Hello, World!"
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=9000)
  • If you set the x-fc-status header, you can report the failure to Function Compute and print the error stack trace to the logs when your function encounters an error. For example, after you set the x-fc-status response header to 404, Function Compute identifies the invocation as a failure with an InvocationError type, and the invocation result is mock exception. The following app.py file provides an example:

    @app.route('/', defaults={'path': ''})
    @app.route('/&lt;path:path&gt;', methods=['GET', 'POST', 'PUT', 'DELETE'])
    def hello_world(path):
        rid = request.headers.get(REQUEST_ID_HEADER)
        print("FC Invoke Start RequestId: " + rid)
        try:
            raise Exception("mock exception")
        except Exception as e:
            print("FC Invoke End RequestId: " + rid + ", Error: Unhandled Exception")
            print(str(e))
            return str(e), 404, [{"x-fc-status", "404"}]
Note

In the returned HTTP response, we recommend setting both the status code and the x-fc-status header.

Code example

When you configure a trigger for your function, you can implement an HTTP server in any programming language. This topic uses Python as an example.

Note

This sample code requires a Python environment and the Flask library. We recommend that you create the function by selecting Web Function and use Python 3.10 as the runtime.

import os
from flask import Flask
from flask import request
REQUEST_ID_HEADER = 'x-fc-request-id'
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def hello_world(path):
    rid = request.headers.get(REQUEST_ID_HEADER)
    data = request.stream.read()
    print("Path: " + path)
    print("Data: " + str(data))
    return "Hello, World!", 200, [('Function-Name', os.getenv('FC_FUNCTION_NAME'))]
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)
            

The code works as follows:

  • @app.route('/', defaults={'path': ''}): This is the default route that corresponds to the root path.

  • @app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE']): This is a dynamic route with a path parameter that can handle GET, POST, PUT, and DELETE requests. This route passes the path parameter's value to the hello_world function as the path argument.

  • rid = request.headers.get(REQUEST_ID_HEADER): Gets the value of the x-fc-request-id field from the request header.

  • data = request.stream.read(): Reads the content of the request and assigns it to the data variable.

  • return "Hello, World!", 200, [('Function-Name', os.getenv('FC_FUNCTION_NAME'))]: Returns a response body that contains "Hello, World!", a status code of 200, and the Function-Name response header.