In a custom runtime, your HTTP server handles event-driven invocations through a endpoint. Function Compute forwards the event payload and common headers to this endpoint, and your server returns the result as the response body.POST /invoke
Quick start
The following Flask example on Python 3.10 shows a minimal event handler:
from flask import Flask, request
REQUEST_ID_HEADER = 'x-fc-request-id'
app = Flask(__name__)
@app.route("/invoke", methods=["POST"])
def handler():
# Extract the request ID from common headers
rid = request.headers.get(REQUEST_ID_HEADER)
print("FC Invoke Start RequestId: " + rid)
# Read the event payload
data = request.stream.read()
print(str(data))
print("FC Invoke End RequestId: " + rid)
# Return the response body
return "Hello, World!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000)Key points:
@app.route("/invoke", methods=["POST"])registers the handler for thepath.POST /invokereads the request ID from the common headers.request.headers.get(REQUEST_ID_HEADER)reads the event payload from the request body.request.stream.read()sends the response body back to the caller.return "Hello, World!"
How it works
When a function is invoked, Function Compute routes the request to your HTTP server in three steps:
Function Compute sends the event payload as the request body to
POST /invokeon your HTTP server, along with common headers that carry runtime context (request ID, function name, credentials, and more).Your HTTP server processes the event and runs your business logic.
Your server returns the result as the response body. Function Compute delivers this body to the caller.
Function Compute also sends a POST /initialize request when a new instance starts. Implement this path if your function requires one-time initialization logic such as loading models or establishing database connections.
Request and response specification
Request
| Component | Details |
|---|---|
| Method and path | |
| Headers | Common headers, including x-fc-request-id, function metadata, and temporary credentials. |
| Body | The function input -- the payload specified when calling the InvokeFunction API. |
| Content-Type | |
Response
Return the function result as the response body. The caller receives this body as the invocation output.
Event handlers only return the response body. Status codes and response headers are ignored. For example, if your Flask handler returns , the status code return "Hello, World!", 400, [('Author', 'Aliyun-FC')]400 and the Author header do not take effect.
Examples for other languages
You can use Serverless Devs to migrate your applications to Function Compute with a few clicks. The following example shows how to use Serverless Devs to deploy and invoke a function in an efficient manner. You can modify the sample code based on your business requirements.