Request handler
A request handler is a method used to handle each function invocation. When creating a function version, you should specify the entry point that consists of the file name and request handler name (for example, main.handler
).
Note
At any given time, a single function instance processes only one request. This lets you use global variables without having to provide data integrity control.
When invoking the handler, the runtime passes the following arguments:
-
The request body (the
event
parameter):- If the request body is a JSON document, it's converted to a
dict
using thejson.loads
method. - If the function was called with the
integration=raw
query string parameter, the HTTP request body is passed to the function as is, unhandled.
- If the request body is a JSON document, it's converted to a
-
The invocation context (the
context
parameter).The context contains the necessary information about the function version. The structure of this object is described in Invocation context.
Handler types
A function can use both synchronous and asynchronous request handlers.
Synchronous handler
To have the execution result returned, use the return
statement or raise an exception using the raise
statement. A synchronous function must return a result or throw an exception.
Asynchronous handler
A handler can be an async def
asynchronous function. In this case you can use the following statements:
return
: Returns the function response.raise
: Reports an error to the runtime environment.await
: Tracks the execution of asynchronous function invocations.
Note
The service only supports the asyncio
library as a runtime environment for asynchronous functions.
To learn more about programming using the async/await
syntax, see the relevant section of the documentation.
Examples
HTTP request structure output
The following function outputs the request structure and invocation context to both the execution log and function response:
import json
def handler(event, context):
return {
'statusCode': 200,
'body': json.dumps({
'event': event,
}),
}