Package: lambda-handlers
python-aws-lambda-handlersAn 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 theAPACHE2.QuickstartInstallationTo install the latest version of lambda-handlers simply run:pipinstalllambda-handlersIf you are going to use validation, we have examples that work withMarshmalloworjsonschema.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 thehttp_handlerdecorator 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 Handlerfromlambda_handlers.handlersimporthttp_handler@http_handler()defhandler(event,context):returnevent['body']ExamplesHTTP handlersSkipping the CORS headers default and configuring it.fromlambda_handlers.handlersimporthttp_handlerfromlambda_handlers.responseimportcors@http_handler(cors=cors(origin='localhost',credentials=False))defhandler(event,context):return{'message':'Hello World!'}awslambdainvoke--function-nameexampleresponse.json
catresponse.json{"headers":{"Access-Control-Allow-Origin":"localhost","Content-Type":"application/json"},"statusCode":200,"body":"{\"message\": \"Hello World!\"}"}ValidationUsing jsonschema to validate a User model as input.fromtypingimportAny,Dict,List,Tuple,Unionimportjsonschemafromlambda_handlers.handlersimporthttp_handlerfromlambda_handlers.errorsimportEventValidationErrorclassSchemaValidator:"""A payload validator that uses jsonschema schemas."""@classmethoddefvalidate(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))iferrors:field_errors=sorted(validator.iter_errors(instance),key=lambdaerror:error.path)raiseEventValidationError(field_errors)@staticmethoddefformat_errors(errors:List[Dict[str,Any]])->List[Dict[str,Any]]:"""Re-format the errors from JSONSchema."""path_errors:Dict[str,List[str]]=defaultdict(list)forerrorinerrors:path_errors[error.path.pop()].append(error.message)return[{path:messages}forpath,messagesinpath_errors.items()]user_schema:Dict[str,Any]={'type':'object','properties':{'user_id':{'type':'number'},},}@http_handler()defhandler(event,context):user=event['body']SchemaValidator.validate(user,user_schema)returnuserawslambdainvoke--function-nameexample--payload'{"body": {"user_id": 42}}'response.json
catresponse.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.fromtypingimportAny,Dict,List,Tuple,UnionfrommarshmallowimportSchema,fields,ValidationErrorfromlambda_handlers.handlersimporthttp_handlerfromlambda_handlers.errorsimportEventValidationErrorclassSchemaValidator:"""A data validator that uses Marshmallow schemas."""@classmethoddefvalidate(cls,instance:Any,schema:Schema)->Any:"""Return the data or raise EventValidationError if any error from validating `instance` against `schema`."""try:returnschema.load(instance)exceptValidationErroraserror:raiseEventValidationError(error.messages)classUserSchema(Schema):user_id=fields.Integer(required=True)@http_handler()defhandler(event,context):user=event['body']SchemaValidator.validate(user,UserSchema())returnuserawslambdainvoke--function-nameexample--payload'{"body": {"user_id": 42}}'response.json
catresponse.json{"headers":{"Access-Control-Allow-Credentials":true,"Access-Control-Allow-Origin":"*","Content-Type":"application/json"},"statusCode":200,"body":"{\"user_id\": 42}"}awslambdainvoke--function-nameexample--payload'{"body": {"user_id": "peter"}}'response.json
catresponse.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.\"]}"}HeadersCorsfromlambda_handlers.handlersimporthttp_handlerfromlambda_handlers.responseimportcors@http_handler(cors=cors(origin='example.com',credentials=False))defhandler(event,context):return{'message':'Hello World!'}awslambdainvoke--function-nameexampleresponse.json
catresponse.json{"headers":{"Access-Control-Allow-Origin":"example.com","Content-Type":"application/json"},"statusCode":200,"body":"{\"message\": \"Hello World!\"}"}ErrorsLambdaHandlerErrorBadRequestErrorForbiddenErrorInternalServerErrorNotFoundErrorFormatErrorValidationErrorShare the LoveLike this project?
Please give it a ★ onour GitHub!Related ProjectsCheck 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.HelpGot a question?File a GitHubissue.ContributingBug Reports & Feature RequestsPlease use theissue trackerto report any bugs or file feature requests.DevelopingIf 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.Forkthe repo on GitHubClonethe project to your own machineCommitchanges to your own branchPushyour work back up to your forkSubmit aPull Requestso that we can review your changesNOTE:Be sure to merge the latest changes from "upstream" before making a pull request!LicenseSeeLICENSEfor 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.