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.8.tar.gz (18.2 kB view details)

Uploaded Source

Built Distribution

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

Uploaded Python 3

File details

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

File metadata

  • Download URL: lambda-handlers-3.0.8.tar.gz
  • Upload date:
  • Size: 18.2 kB
  • Tags: Source
  • Uploaded using 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

File hashes

Hashes for lambda-handlers-3.0.8.tar.gz
Algorithm Hash digest
SHA256 29f10c9169fb6ce607d9a46521ec22c334b055e5f28144148c237edb89f5db55
MD5 5f4adfd8fe1d247d8fb31a7fa0be498a
BLAKE2b-256 98096f4123147c31390e6c820be0e8598c0dfe0f5a2f1d6ed648daeebc84e973

See more details on using hashes here.

File details

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

File metadata

  • Download URL: lambda_handlers-3.0.8-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/47.1.0 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.7.9

File hashes

Hashes for lambda_handlers-3.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 e5948c7ab32491fb5d6a94898aedd23b733c7f021f80a53361184dc8f5fe625c
MD5 2252a8e121bcb76a13559206c2a2b372
BLAKE2b-256 e8e959279597893889940fab6770ac71c1919a86b42dfac3436843609e73d1e9

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