python-aws-lambda-handlers

An opinionated Python package that facilitates specifying AWS Lambda handlers including input validation, error handling and response formatting.
It's 100% Open Source and licensed under the APACHE2.
Quickstart
Installation
To install the latest version of lambda-handlers simply run:
pip install lambda-handlers
If you are going to use validation, we have examples that work with Marshmallow or jsonschema.
But you can adapt a LambdaHandler to use your favourite validation module. Please share it with us or create an issue if you need any help with that.
By default the http_handler decorator makes sure of parsing the request body
as JSON, and also formats the response as JSON with:
- an adequate statusCode,
- CORS headers, and
- the handler return value in the body.
Basic ApiGateway Proxy Handler
from lambda_handlers.handlers import http_handler
@http_handler()
def handler(event, context):
return event['body']
Examples
HTTP handlers
Skipping the CORS headers default and configuring it.
from lambda_handlers.handlers import http_handler
from lambda_handlers.response import cors
@http_handler(cors=cors(origin='localhost', credentials=False))
def handler(event, context):
return {
'message': 'Hello World!'
}
aws lambda invoke --function-name example response.json
cat response.json
{
"headers":{
"Access-Control-Allow-Origin": "localhost",
"Content-Type": "application/json"
},
"statusCode": 200,
"body": "{\"message\": \"Hello World!\"}"
}
Validation
Using jsonschema to validate a User model as input.
from typing import Any, Dict, List, Tuple, Union
import jsonschema
from lambda_handlers.handlers import http_handler
from lambda_handlers.errors import EventValidationError
class SchemaValidator:
"""A payload validator that uses jsonschema schemas."""
@classmethod
def validate(cls, instance, schema: Dict[str, Any]):
"""
Raise EventValidationError (if any error) from validating
`instance` against `schema`.
"""
validator = jsonschema.Draft7Validator(schema)
errors = list(validator.iter_errors(instance))
if errors:
field_errors = sorted(validator.iter_errors(instance), key=lambda error: error.path)
raise EventValidationError(field_errors)
@staticmethod
def format_errors(errors: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Re-format the errors from JSONSchema."""
path_errors: Dict[str, List[str]] = defaultdict(list)
for error in errors:
path_errors[error.path.pop()].append(error.message)
return [{path: messages} for path, messages in path_errors.items()]
user_schema: Dict[str, Any] = {
'type': 'object',
'properties': {
'user_id': {'type': 'number'},
},
}
@http_handler()
def handler(event, context):
user = event['body']
SchemaValidator.validate(user, user_schema)
return user
aws lambda invoke --function-name example --payload '{"body": {"user_id": 42}}' response.json
cat response.json
{
"headers":{
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
"statusCode": 200,
"body": "{\"user_id\": 42}"
}
Using Marshmallow to validate a User model as input body and response body.
from typing import Any, Dict, List, Tuple, Union
from marshmallow import Schema, fields, ValidationError
from lambda_handlers.handlers import http_handler
from lambda_handlers.errors import EventValidationError
class SchemaValidator:
"""A data validator that uses Marshmallow schemas."""
@classmethod
def validate(cls, instance: Any, schema: Schema) -> Any:
"""Return the data or raise EventValidationError if any error from validating `instance` against `schema`."""
try:
return schema.load(instance)
except ValidationError as error:
raise EventValidationError(error.messages)
class UserSchema(Schema):
user_id = fields.Integer(required=True)
@http_handler()
def handler(event, context):
user = event['body']
SchemaValidator.validate(user, UserSchema())
return user
aws lambda invoke --function-name example --payload '{"body": {"user_id": 42}}' response.json
cat response.json
{
"headers":{
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
"statusCode": 200,
"body": "{\"user_id\": 42}"
}
aws lambda invoke --function-name example --payload '{"body": {"user_id": "peter"}}' response.json
cat response.json
{
"headers":{
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
"statusCode": 400,
"body": "{\"errors\": {\"user_id\": [\"Not a valid integer.\"]}"
}
Headers
Cors
from lambda_handlers.handlers import http_handler
from lambda_handlers.response import cors
@http_handler(cors=cors(origin='example.com', credentials=False))
def handler(event, context):
return {
'message': 'Hello World!'
}
aws lambda invoke --function-name example response.json
cat response.json
{
"headers":{
"Access-Control-Allow-Origin": "example.com",
"Content-Type": "application/json"
},
"statusCode": 200,
"body": "{\"message\": \"Hello World!\"}"
}
Errors
LambdaHandlerError
BadRequestError
ForbiddenError
InternalServerError
NotFoundError
FormatError
ValidationError
Share the Love
Like this project? Please give it a ★ on our GitHub!
Related Projects
Check out these related projects.
- node-aws-lambda-handlers - An opinionated Typescript package that facilitates specifying AWS Lambda handlers including input validation, error handling and response formatting.
Help
Got a question?
File a GitHub issue.
Contributing
Bug Reports & Feature Requests
Please use the issue tracker to report any bugs or file feature requests.
Developing
If you are interested in being a contributor and want to get involved in developing this project, we would love to hear from you!
In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow.
- Fork the repo on GitHub
- Clone the project to your own machine
- Commit changes to your own branch
- Push your work back up to your fork
- Submit a Pull Request so that we can review your changes
NOTE: Be sure to merge the latest changes from "upstream" before making a pull request!
License
See LICENSE for full details.
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
Metadata
Release files for lambda-handlers 3.0.8
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| lambda-handlers-3.0.8.tar.gz | 18.2 kB | Without provenance | Details for lambda-handlers-3.0.8.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| lambda_handlers-3.0.8-py3-none-any.whl | Python 3 | none | any | Details for lambda_handlers-3.0.8-py3-none-any.whl |
Total release size: 35.3 kB
Release files / lambda-handlers-3.0.8.tar.gz
| Download URL | lambda-handlers-3.0.8.tar.gz |
|---|---|
| Size | 18.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
29f10c9169fb6ce607d9a46521ec22c334b055e5f28144148c237edb89f5db55
|
|
BLAKE2b-256 checksum How to use checksums |
98096f4123147c31390e6c820be0e8598c0dfe0f5a2f1d6ed648daeebc84e973
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/47.1.0 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.7.9
|
Release files / lambda_handlers-3.0.8-py3-none-any.whl
| Download URL | lambda_handlers-3.0.8-py3-none-any.whl |
|---|---|
| Size | 17.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e5948c7ab32491fb5d6a94898aedd23b733c7f021f80a53361184dc8f5fe625c
|
|
BLAKE2b-256 checksum How to use checksums |
e8e959279597893889940fab6770ac71c1919a86b42dfac3436843609e73d1e9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/47.1.0 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.7.9
|
Security for lambda-handlers 3.0.8
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.