You must have an existing API Gateway Proxy integration or ALB configured to invoke your Lambda function. There is no additional permissions or dependencies required to use this utility.
This is the sample infrastructure for API Gateway we are using for the examples in this documentation.
AWSTemplateFormatVersion:'2010-09-09'Transform:AWS::Serverless-2016-10-31Description:Hello world event handler API GatewayGlobals:Api:TracingEnabled:trueCors:# see CORS sectionAllowOrigin:"'https://example.com'"AllowHeaders:"'Content-Type,Authorization,X-Amz-Date'"MaxAge:"'300'"BinaryMediaTypes:# see Binary responses section-'*~1*'# converts to */* for any binary typeFunction:Timeout:5Runtime:python3.8Tracing:ActiveEnvironment:Variables:LOG_LEVEL:INFOPOWERTOOLS_LOGGER_SAMPLE_RATE:0.1POWERTOOLS_LOGGER_LOG_EVENT:truePOWERTOOLS_METRICS_NAMESPACE:MyServerlessApplicationPOWERTOOLS_SERVICE_NAME:my_api-serviceResources:ApiFunction:Type:AWS::Serverless::FunctionProperties:Handler:app.lambda_handlerCodeUri:api_handler/Description:API handler functionEvents:ApiEvent:Type:ApiProperties:Path:/{proxy+}# Send requests on any path to the lambda functionMethod:ANY# Send requests using any http method to the lambda function
When using Amazon API Gateway REST API to front your Lambda functions, you can use APIGatewayRestResolver.
Here's an example on how we can handle the /hello path.
Info
We automatically serialize Dict responses as JSON, trim whitespace for compact responses, and set content-type to application/json.
1 2 3 4 5 6 7 8 9101112131415161718
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportAPIGatewayRestResolvertracer=Tracer()logger=Logger()app=APIGatewayRestResolver()@app.get("/hello")@tracer.capture_methoddefget_hello_universe():return{"message":"hello universe"}# You can continue to use other utilities just as before@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
This utility uses path and httpMethod to route to the right function. This helps make unit tests and local invocation easier too.
When using Amazon API Gateway HTTP API to front your Lambda functions, you can use APIGatewayHttpResolver.
Note
Using HTTP API v1 payload? Use APIGatewayRestResolver instead. APIGatewayHttpResolver defaults to v2 payload.
Here's an example on how we can handle the /hello path.
Using HTTP API resolver
1 2 3 4 5 6 7 8 9101112131415161718
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportAPIGatewayHttpResolvertracer=Tracer()logger=Logger()app=APIGatewayHttpResolver()@app.get("/hello")@tracer.capture_methoddefget_hello_universe():return{"message":"hello universe"}# You can continue to use other utilities just as before@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_HTTP)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
When using Amazon Application Load Balancer to front your Lambda functions, you can use ALBResolver.
Using ALB resolver
1 2 3 4 5 6 7 8 9101112131415161718
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportALBResolvertracer=Tracer()logger=Logger()app=ALBResolver()@app.get("/hello")@tracer.capture_methoddefget_hello_universe():return{"message":"hello universe"}# You can continue to use other utilities just as before@logger.inject_lambda_context(correlation_id_path=correlation_paths.APPLICATION_LOAD_BALANCER)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
You can use /path/{dynamic_value} when configuring dynamic URL paths. This allows you to define such dynamic value as part of your function signature.
1 2 3 4 5 6 7 8 9101112131415161718
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportAPIGatewayRestResolvertracer=Tracer()logger=Logger()app=APIGatewayRestResolver()@app.get("/hello/<name>")@tracer.capture_methoddefget_hello_you(name):return{"message":f"hello {name}"}# You can continue to use other utilities just as before@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportAPIGatewayRestResolvertracer=Tracer()logger=Logger()app=APIGatewayRestResolver()@app.get("/<message>/<name>")@tracer.capture_methoddefget_message(message,name):return{"message":f"{message}, {name}"}# You can continue to use other utilities just as before@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
You can use named decorators to specify the HTTP method that should be handled in your functions. As well as the
get method already shown above, you can use post, put, patch, delete, and patch.
1 2 3 4 5 6 7 8 91011121314151617181920
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportAPIGatewayRestResolvertracer=Tracer()logger=Logger()app=APIGatewayRestResolver()# Only POST HTTP requests to the path /hello will route to this function@app.post("/hello")@tracer.capture_methoddefget_hello_you():name=app.current_event.json_body.get("name")return{"message":f"hello {name}"}# You can continue to use other utilities just as before@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
If you need to accept multiple HTTP methods in a single function, you can use the route method and pass a list of
HTTP methods.
1 2 3 4 5 6 7 8 91011121314151617181920
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportAPIGatewayRestResolvertracer=Tracer()logger=Logger()app=APIGatewayRestResolver()# PUT and POST HTTP requests to the path /hello will route to this function@app.route("/hello",method=["PUT","POST"])@tracer.capture_methoddefget_hello_you():name=app.current_event.json_body.get("name")return{"message":f"hello {name}"}# You can continue to use other utilities just as before@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
Within app.current_event property, you can access query strings as dictionary via query_string_parameters, or by name via get_query_string_value method.
You can access the raw payload via body property, or if it's a JSON string you can quickly deserialize it via json_body property.
Accessing query strings, JSON payload, and raw payload
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportcontent_typesfromaws_lambda_powertools.event_handler.api_gatewayimportAPIGatewayRestResolver,Responsefromaws_lambda_powertools.event_handler.exceptionsimportNotFoundErrortracer=Tracer()logger=Logger()app=APIGatewayRestResolver()@app.not_found@tracer.capture_methoddefhandle_not_found_errors(exc:NotFoundError)->Response:# Return 418 upon 404 errorslogger.info(f"Not found route: {app.current_event.path}")returnResponse(status_code=418,content_type=content_types.TEXT_PLAIN,body="I'm a teapot!")@app.get("/catch/me/if/you/can")@tracer.capture_methoddefcatch_me_if_you_can():return{"message":"oh hey"}@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
You can use exception_handler decorator with any Python exception. This allows you to handle a common exception outside your route, for example validation errors.
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportcontent_typesfromaws_lambda_powertools.event_handler.api_gatewayimportAPIGatewayRestResolver,Responsetracer=Tracer()logger=Logger()app=APIGatewayRestResolver()@app.exception_handler(ValueError)defhandle_value_error(ex:ValueError):metadata={"path":app.current_event.path}logger.error(f"Malformed request: {ex}",extra=metadata)returnResponse(status_code=400,content_type=content_types.TEXT_PLAIN,body="Invalid request",)@app.get("/hello")@tracer.capture_methoddefhello_name():name=app.current_event.get_query_string_value(name="name")ifnameisnotNone:raiseValueError("name query string must be present")return{"message":f"hello {name}"}@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
When using Custom Domain API Mappings feature, you must use strip_prefixes param in the APIGatewayRestResolver constructor.
Scenario: You have a custom domain api.mydomain.dev and set an API Mapping payment to forward requests to your Payments API, the path argument will be /payment/<your_actual_path>.
This will lead to a HTTP 404 despite having your Lambda configured correctly. See the example below on how to account for this change.
After removing a path prefix with strip_prefixes, the new root path will automatically be mapped to the path argument of /.
For example, when using strip_prefixes value of /pay, there is no difference between a request path of /pay and /pay/; and the path argument would be defined as /.
You can configure CORS at the APIGatewayRestResolver constructor via cors parameter using the CORSConfig class.
This will ensure that CORS headers are always returned as part of the response when your functions match the path invoked.
1 2 3 4 5 6 7 8 910111213141516171819202122232425
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handler.api_gatewayimportAPIGatewayRestResolver,CORSConfigtracer=Tracer()logger=Logger()cors_config=CORSConfig(allow_origin="https://example.com",max_age=300)app=APIGatewayRestResolver(cors=cors_config)@app.get("/hello/<name>")@tracer.capture_methoddefget_hello_you(name):return{"message":f"hello {name}"}@app.get("/hello",cors=False)# optionally exclude CORS from response, if needed@tracer.capture_methoddefget_hello_no_cors_needed():return{"message":"hello, no CORS needed for this path ;)"}# You can continue to use other utilities just as before@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)@tracer.capture_lambda_handlerdeflambda_handler(event,context):returnapp.resolve(event,context)
Pre-flight (OPTIONS) calls are typically handled at the API Gateway level as per our sample infrastructure, no Lambda integration necessary. However, ALB expects you to handle pre-flight requests.
You can use the Response class to have full control over the response, for example you might want to add additional headers or set a custom Content-type.
1 2 3 4 5 6 7 8 910111213141516171819
importjsonfromaws_lambda_powertools.event_handler.api_gatewayimportAPIGatewayRestResolver,Responseapp=APIGatewayRestResolver()@app.get("/hello")defget_hello_you():payload=json.dumps({"message":"I'm a teapot"})custom_headers={"X-Custom":"X-Value"}returnResponse(status_code=418,content_type="application/json",body=payload,headers=custom_headers,)deflambda_handler(event,context):returnapp.resolve(event,context)
For convenience, we automatically base64 encode binary responses. You can also use in combination with compress parameter if your client supports gzip.
Like compress feature, the client must send the Accept header with the correct media type.
Warning
This feature requires API Gateway to configure binary media types, see our sample infrastructure for reference.
importjsonfromenumimportEnumfromjsonimportJSONEncoderfromtypingimportDictfromaws_lambda_powertools.event_handlerimportAPIGatewayRestResolverclassCustomEncoder(JSONEncoder):"""Your customer json encoder"""defdefault(self,obj):ifisinstance(obj,Enum):returnobj.valuetry:iterable=iter(obj)exceptTypeError:passelse:returnsorted(iterable)returnJSONEncoder.default(self,obj)defcustom_serializer(obj)->str:"""Your custom serializer function APIGatewayRestResolver will use"""returnjson.dumps(obj,cls=CustomEncoder)# Assigning your custom serializerapp=APIGatewayRestResolver(serializer=custom_serializer)classColor(Enum):RED=1BLUE=2@app.get("/colors")defget_color()->Dict:return{# Color.RED will be serialized to 1 as expected now"color":Color.RED,"variations":{"light","dark"},}
As you grow the number of routes a given Lambda function should handle, it is natural to split routes into separate files to ease maintenance - That's where the Router feature is useful.
Let's assume you have app.py as your Lambda function entrypoint and routes in users.py, this is how you'd use the Router feature.
We import Router instead of APIGatewayRestResolver; syntax wise is exactly the same.
importitertoolsfromtypingimportDictfromaws_lambda_powertoolsimportLoggerfromaws_lambda_powertools.event_handler.api_gatewayimportRouterlogger=Logger(child=True)router=Router()USERS={"user1":"details_here","user2":"details_here","user3":"details_here"}@router.get("/users")defget_users()->Dict:# /users?limit=1pagination_limit=router.current_event.get_query_string_value(name="limit",default_value=10)logger.info(f"Fetching the first {pagination_limit} users...")ret=dict(itertools.islice(USERS.items(),int(pagination_limit)))return{"items":[ret]}@router.get("/users/<username>")defget_user(username:str)->Dict:logger.info(f"Fetching username {username}")return{"details":USERS.get(username,{})}# many other related /users routing
We use include_router method and include all user routers registered in the router global object.
In the previous example, users.py routes had a /users prefix. This might grow over time and become repetitive.
When necessary, you can set a prefix when including a router object. This means you could remove /users prefix in users.py altogether.
1 2 3 4 5 6 7 8 910111213
fromtypingimportDictfromaws_lambda_powertools.event_handlerimportAPIGatewayRestResolverfromaws_lambda_powertools.utilities.typingimportLambdaContextimportusersapp=APIGatewayRestResolver()app.include_router(users.router,prefix="/users")# prefix '/users' to any route in `users.router`deflambda_handler(event:Dict,context:LambdaContext):returnapp.resolve(event,context)
1 2 3 4 5 6 7 8 910111213141516171819
fromtypingimportDictfromaws_lambda_powertoolsimportLoggerfromaws_lambda_powertools.event_handler.api_gatewayimportRouterlogger=Logger(child=True)router=Router()USERS={"user1":"details","user2":"details","user3":"details"}@router.get("/")# /users, when we set the prefix in app.pydefget_users()->Dict:...@router.get("/<username>")defget_user(username:str)->Dict:...# many other related /users routing
This sample project contains a Users function with two distinct set of routes, /users and /health. The layout optimizes for code sharing, no custom build tooling, and it uses Lambda Layers to install Lambda Powertools.
1 2 3 4 5 6 7 8 910111213141516171819202122232425
.├──Pipfile# project app & dev dependencies; poetry, pipenv, etc.├──Pipfile.lock├──README.md├──src│├──__init__.py│├──requirements.txt# sam build detect it automatically due to CodeUri: src, e.g. pipenv lock -r > src/requirements.txt│└──users│├──__init__.py│├──main.py# this will be our users Lambda fn; it could be split in folders if we want separate fns same code base│└──routers# routers module│├──__init__.py│├──health.py# /users routes, e.g. from routers import users; users.router│└──users.py# /users routes, e.g. from .routers import users; users.router├──template.yml# SAM template.yml, CodeUri: src, Handler: users.main.lambda_handler└──tests├──__init__.py├──unit│├──__init__.py│└──test_users.py# unit tests for the users router│└──test_health.py# unit tests for the health router└──functional├──__init__.py├──conftest.py# pytest fixtures for the functional tests└──test_main.py# functional tests for the main lambda handler
AWSTemplateFormatVersion:'2010-09-09'Transform:AWS::Serverless-2016-10-31Description:Example service with multiple routesGlobals:Function:Timeout:10MemorySize:512Runtime:python3.9Tracing:ActiveArchitectures:-x86_64Environment:Variables:LOG_LEVEL:INFOPOWERTOOLS_LOGGER_LOG_EVENT:truePOWERTOOLS_METRICS_NAMESPACE:MyServerlessApplicationPOWERTOOLS_SERVICE_NAME:usersResources:UsersService:Type:AWS::Serverless::FunctionProperties:Handler:users.main.lambda_handlerCodeUri:srcLayers:# Latest version: https://awslabs.github.io/aws-lambda-powertools-python/latest/#lambda-layer-!Subarn:aws:lambda:${AWS::Region}:017000801446:layer:AWSLambdaPowertoolsPython:4Events:ByUser:Type:ApiProperties:Path:/users/{name}Method:GETAllUsers:Type:ApiProperties:Path:/usersMethod:GETHealthCheck:Type:ApiProperties:Path:/statusMethod:GETOutputs:UsersApiEndpoint:Description:"APIGatewayendpointURLforProdenvironmentforUsersFunction"Value:!Sub"https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod"AllUsersURL:Description:"URLtofetchallregisteredusers"Value:!Sub"https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/users"ByUserURL:Description:"URLtoretrievedetailsbyuser"Value:!Sub"https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/users/test"UsersServiceFunctionArn:Description:"UsersLambdaFunctionARN"Value:!GetAttUsersService.Arn
This utility is optimized for fast startup, minimal feature set, and to quickly on-board customers familiar with frameworks like Flask — it's not meant to be a fully fledged framework.
Event Handler naturally leads to a single Lambda function handling multiple routes for a given service, which can be eventually broken into multiple functions.
Both single (monolithic) and multiple functions (micro) offer different set of trade-offs worth knowing.
Tip
TL;DR. Start with a monolithic function, add additional functions with new handlers, and possibly break into micro functions if necessary.
A monolithic function means that your final code artifact will be deployed to a single function. This is generally the best approach to start.
Benefits
Code reuse. It's easier to reason about your service, modularize it and reuse code as it grows. Eventually, it can be turned into a standalone library.
No custom tooling. Monolithic functions are treated just like normal Python packages; no upfront investment in tooling.
Faster deployment and debugging. Whether you use all-at-once, linear, or canary deployments, a monolithic function is a single deployable unit. IDEs like PyCharm and VSCode have tooling to quickly profile, visualize, and step through debug any Python package.
Downsides
Cold starts. Frequent deployments and/or high load can diminish the benefit of monolithic functions depending on your latency requirements, due to Lambda scaling model. Always load test to pragmatically balance between your customer experience and development cognitive load.
Granular security permissions. The micro function approach enables you to use fine-grained permissions & access controls, separate external dependencies & code signing at the function level. Conversely, you could have multiple functions while duplicating the final code artifact in a monolithic approach.
Regardless, least privilege can be applied to either approaches.
Higher risk per deployment. A misconfiguration or invalid import can cause disruption if not caught earlier in automated testing. Multiple functions can mitigate misconfigurations but they would still share the same code artifact. You can further minimize risks with multiple environments in your CI/CD pipeline.
A micro function means that your final code artifact will be different to each function deployed. This is generally the approach to start if you're looking for fine-grain control and/or high load on certain parts of your service.
Benefits
Granular scaling. A micro function can benefit from the Lambda scaling model to scale differently depending on each part of your application. Concurrency controls and provisioned concurrency can also be used at a granular level for capacity management.
Discoverability. Micro functions are easier do visualize when using distributed tracing. Their high-level architectures can be self-explanatory, and complexity is highly visible — assuming each function is named to the business purpose it serves.
Package size. An independent function can be significant smaller (KB vs MB) depending on external dependencies it require to perform its purpose. Conversely, a monolithic approach can benefit from Lambda Layers to optimize builds for external dependencies.
Downsides
Upfront investment. Python ecosystem doesn't use a bundler — you need a custom build tooling to ensure each function only has what it needs and account for C bindings for runtime compatibility. Operations become more elaborate — you need to standardize tracing labels/annotations, structured logging, and metrics to pinpoint root causes.
Engineering discipline is necessary for both approaches. Micro-function approach however requires further attention in consistency as the number of functions grow, just like any distributed system.
Harder to share code. Shared code must be carefully evaluated to avoid unnecessary deployments when that changes. Equally, if shared code isn't a library,
your development, building, deployment tooling need to accommodate the distinct layout.
Slower safe deployments. Safely deploying multiple functions require coordination — AWS CodeDeploy deploys and verifies each function sequentially. This increases lead time substantially (minutes to hours) depending on the deployment strategy you choose. You can mitigate it by selectively enabling it in prod-like environments only, and where the risk profile is applicable.
Automated testing, operational and security reviews are essential to stability in either approaches.
fromaws_lambda_powertoolsimportLoggerfromaws_lambda_powertools.loggingimportcorrelation_pathsfromaws_lambda_powertools.event_handlerimportAPIGatewayRestResolverlogger=Logger()app=APIGatewayRestResolver()# API Gateway REST API (v1)@app.get("/hello")defget_hello_universe():return{"message":"hello universe"}# You can continue to use other utilities just as before@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)deflambda_handler(event,context):returnapp.resolve(event,context)
What's the difference between this utility and frameworks like Chalice?
Chalice is a full featured microframework that manages application and infrastructure. This utility, however, is largely focused on routing to reduce boilerplate and expects you to setup and manage infrastructure with your framework of choice.
It's been superseded by more explicit resolvers like APIGatewayRestResolver, APIGatewayHttpResolver, and ALBResolver.
ApiGatewayResolver handled multiple types of event resolvers for convenience via proxy_type param. However,
it made it impossible for static checkers like Mypy and IDEs IntelliSense to know what properties a current_event would have due to late bound resolution.
This provided a suboptimal experience for customers not being able to find all properties available besides common ones between API Gateway REST, HTTP, and ALB - while manually annotating app.current_event would work it is not the experience we want to provide to customers.
ApiGatewayResolver will be deprecated in v2 and have appropriate warnings as soon as we have a v2 draft.