Skip to main content

A collection of useful decorators for making AWS Lambda handlers

Project description

enter-at

python-aws-lambda-handlers Build Status Release CodeClimate

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.

  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

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lambda-handlers-3.0.5.tar.gz (19.3 kB view details)

Uploaded Source

Built Distribution

lambda_handlers-3.0.5-py3-none-any.whl (17.1 kB view details)

Uploaded Python 3

File details

Details for the file lambda-handlers-3.0.5.tar.gz.

File metadata

  • Download URL: lambda-handlers-3.0.5.tar.gz
  • Upload date:
  • Size: 19.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.8.6

File hashes

Hashes for lambda-handlers-3.0.5.tar.gz
Algorithm Hash digest
SHA256 fc10c4e758947b45c5f8f877f4b8ed35fee3dfb518ab9149f5c4abd4b0dc5e7b
MD5 fcb75265200e397d2ccac4f87d3aa0b7
BLAKE2b-256 bab11f65e10efe09c3bbf8d37465358efb76579ca5253e68fa9d4be175f0eb9c

See more details on using hashes here.

File details

Details for the file lambda_handlers-3.0.5-py3-none-any.whl.

File metadata

  • Download URL: lambda_handlers-3.0.5-py3-none-any.whl
  • Upload date:
  • Size: 17.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.8.6

File hashes

Hashes for lambda_handlers-3.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 5f7a9eae54bf4feb16c561158f4fa2711d0290fbe4b745a7c96b851e87276b03
MD5 e42b75d061c5cd78ece15aeb215b84ed
BLAKE2b-256 b8d4606815f7d0f9cfeccba8a196b371114a5855c8208b858d4b255690b72d4f

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page