An open API service indexing awesome lists of open source software.

https://github.com/enter-at/python-aws-lambda-handlers

An opinionated Python package that facilitates specifying AWS Lambda handlers including input validation, error handling and response formatting.
https://github.com/enter-at/python-aws-lambda-handlers

aws-lambda http json-schema marshmallow python

Last synced: 4 months ago
JSON representation

An opinionated Python package that facilitates specifying AWS Lambda handlers including input validation, error handling and response formatting.

Awesome Lists containing this project

README

        

[enter-at][website]

# python-aws-lambda-handlers [![Build Status](https://github.com/enter-at/python-aws-lambda-handlers/workflows/Code%20checks%20and%20tests/badge.svg)](https://github.com/enter-at/python-aws-lambda-handlers/actions?query=workflow%3A%22Code+checks+and+tests%22) [![Release](https://img.shields.io/pypi/v/lambda-handlers.svg)](https://pypi.org/project/lambda-handlers/) [![Code Climate Maintainability](https://api.codeclimate.com/v1/badges/852b53c3aab82fe1ebe7/maintainability)](https://codeclimate.com/github/enter-at/python-aws-lambda-handlers/maintainability) [![Code Climate Test Coverage](https://api.codeclimate.com/v1/badges/852b53c3aab82fe1ebe7/test_coverage)](https://codeclimate.com/github/enter-at/python-aws-lambda-handlers/test_coverage)

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](LICENSE).

# Quickstart

## Installation

To install the latest version of lambda-handlers simply run:

```bash
pip install lambda-handlers
```

If you are going to use validation, we have examples that work with
[Marshmallow](https://pypi.org/project/marshmallow/) or
[jsonschema](https://pypi.org/project/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
```python
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.

```python
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!'
}
```

```bash
aws lambda invoke --function-name example response.json
cat response.json
```

```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.

```python
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
```

```bash
aws lambda invoke --function-name example --payload '{"body": {"user_id": 42}}' response.json
cat response.json
```

```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.

```python
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
```

```bash
aws lambda invoke --function-name example --payload '{"body": {"user_id": 42}}' response.json
cat response.json
```

```json
{
"headers":{
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
"statusCode": 200,
"body": "{\"user_id\": 42}"
}
```

```bash
aws lambda invoke --function-name example --payload '{"body": {"user_id": "peter"}}' response.json
cat response.json
```

```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

```python
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!'
}
```

```bash
aws lambda invoke --function-name example response.json
cat response.json
```

```json
{
"headers":{
"Access-Control-Allow-Origin": "example.com",
"Content-Type": "application/json"
},
"statusCode": 200,
"body": "{\"message\": \"Hello World!\"}"
}
```
### Errors

```python
LambdaHandlerError
```
```python
BadRequestError
```
```python
ForbiddenError
```
```python
InternalServerError
```
```python
NotFoundError
```
```python
FormatError
```
```python
ValidationError
```

## Share the Love

Like this project?
Please give it a ★ on [our GitHub](https://github.com/enter-at/python-aws-lambda-handlers)!

## Related Projects

Check out these related projects.

- [node-aws-lambda-handlers](https://github.com/enter-at/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](https://github.com/enter-at/python-aws-lambda-handlers/issues).

## Contributing

### Bug Reports & Feature Requests

Please use the [issue tracker](https://github.com/enter-at/python-aws-lambda-handlers/issues) 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.

1. **Fork** the repo on GitHub
2. **Clone** the project to your own machine
3. **Commit** changes to your own branch
4. **Push** your work back up to your fork
5. 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

[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

See [LICENSE](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.

[website]: https://github.com/enter-at