API Gateway
Event handler for Amazon API Gateway REST/HTTP APIs and Application Loader Balancer (ALB).
Key Features¶
- Lightweight routing to reduce boilerplate for API Gateway REST/HTTP API and ALB
- Seamless support for CORS, binary and Gzip compression
- Integrates with Data classes utilities to easily access event and identity information
- Built-in support for Decimals JSON encoding
- Support for dynamic path expressions
Getting started¶
Required resources¶
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
API Gateway decorator¶
You can define your functions to match a path and HTTP method, when you use the decorator ApiGatewayResolver
.
Here's an example where we have two separate functions to resolve two paths: /hello
.
We automatically serialize Dict
responses as JSON, trim whitespaces for compact responses, and set content-type to application/json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
This utility uses path
and httpMethod
to route to the right function. This helps make unit tests and local invocation easier too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
|
1 2 3 4 5 6 7 8 |
|
HTTP API¶
When using API Gateway HTTP API to front your Lambda functions, you can instruct ApiGatewayResolver
to conform with their contract via proxy_type
param:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
ALB¶
When using ALB to front your Lambda functions, you can instruct ApiGatewayResolver
to conform with their contract via proxy_type
param:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Dynamic routes¶
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 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 |
|
You can also nest paths as configured earlier in our sample infrastructure: /{message}/{name}
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 |
|
Accessing request details¶
By integrating with Data classes utilities, you have access to request details, Lambda context and also some convenient methods.
These are made available in the response returned when instantiating ApiGatewayResolver
, for example app.current_event
and app.lambda_context
.
Query strings and payload¶
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Headers¶
Similarly to Query strings, you can access headers as dictionary via app.current_event.headers
, or by name via get_header_value
.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Raising HTTP errors¶
You can easily raise any HTTP Error back to the client using ServiceError
exception.
If you need to send custom headers, use Response class instead.
Additionally, we provide pre-defined errors for the most popular ones such as HTTP 400, 401, 404, 500.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|
Custom Domain API Mappings¶
When using Custom Domain API Mappings feature, you must use strip_prefixes
param in the ApiGatewayResolver
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 |
|
Note: 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 /
.
Advanced¶
CORS¶
You can configure CORS at the ApiGatewayResolver
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 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 |
|
Optionally disable class on a per path basis with cors=False
parameter
Pre-flight¶
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.
For convenience, we automatically handle that for you as long as you setup CORS in the constructor level.
Defaults¶
For convenience, these are the default values when using CORSConfig
to enable CORS:
Always configure allow_origin
when using in production
Key | Value | Note |
---|---|---|
allow_origin: str |
* |
Only use the default value for development. Never use * for production unless your use case requires it |
allow_headers: List[str] |
[Authorization, Content-Type, X-Amz-Date, X-Api-Key, X-Amz-Security-Token] |
Additional headers will be appended to the default list for your convenience |
expose_headers: List[str] |
[] |
Any additional header beyond the safe listed by CORS specification. |
max_age: int |
`` | Only for pre-flight requests if you choose to have your function to handle it instead of API Gateway |
allow_credentials: bool |
False |
Only necessary when you need to expose cookies, authorization headers or TLS client certificates. |
Fine grained responses¶
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 9 10 11 12 13 14 15 16 17 |
|
```json { "body": "{\"message\":\"I\'m a teapot\"}", "headers": { "Content-Type": "application/json", "X-Custom": "X-Value" }, "isBase64Encoded": false, "statusCode": 418 }
Compress¶
You can compress with gzip and base64 encode your responses via compress
parameter.
The client must send the Accept-Encoding
header, otherwise a normal response will be sent
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 |
|
Binary responses¶
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.
This feature requires API Gateway to configure binary media types, see our sample infrastructure for reference
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 |
|
Debug mode¶
You can enable debug mode via debug
param, or via POWERTOOLS_EVENT_HANDLER_DEBUG
environment variable.
This will enable full tracebacks errors in the response, print request and responses, and set CORS in development mode.
This might reveal sensitive information in your logs and relax CORS restrictions, use it sparingly.
1 2 3 4 5 6 7 8 9 10 |
|
Custom serializer¶
You can instruct API Gateway handler to use a custom serializer to best suit your needs, for example take into account Enums when serializing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
Testing your code¶
You can test your routes by passing a proxy event request where path
and httpMethod
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
FAQ¶
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.
That said, Chalice has native integration with Lambda Powertools if you're looking for a more opinionated and web framework feature set.