DEV Community

criscarba
criscarba

Posted on

Payload Validation in AWS REST API using PYDANTIC

This post will show an example of how to validate the payload received in a REST API developed in Python using SAM (Serverless Application Model). In addition i will show how to deploy it locally.

PYDANTIC provides data validation and settings management using python type annotations. Furthermore PYDANTIC enforces type hints at runtime, and provides user friendly errors when data is invalid.

SAM

Pre-Requistes for this example:

Please make sure you have successfully completed the Pre-Requisites listed above before continue. Reach out me if you have any trouble.

*STEP #1 *— Open VSCode in the directory where the repository was downloaded or cloned:

1

2

STEP #2— Build the REST API with AWS SAM

Open a new Terminal in VSCode and make sure that you are sat into the REST API path where SAM can find the “template.yaml” file and run the command:

SAM BUILD

3

STEP #3 — Start the API Locally

Within the terminar in VSCode run the command

SAM LOCAL START-API

4

5

You will see that the application is running at http://127.0.0.1:3000 (localhost)

STEP #4: — Execute API using POSTMAN

Download POSTMAN from their official site https://www.postman.com/

Create a new workspace and test the API:

Postman

STEP #5: Understand PYDANTIC

As explained above PYDANTIC provides data validation and settings management using python type annotations and enforces type hints at runtime, and provides user friendly errors when data is invalid.

py

Within the “services” folder there is a python code called “event_check.py” that code is a PYDANTIC Class which contains the model of the expected event payload.

py2

STEP #6: Test PYDANTIC Behavior

Now that you understand how to create the model of your event that will allow PYDANTIC to enforce the validation, is time to call the API with with failure payloads and see the outcomes

  • Send an unexpected KEY (table_2):

py5

  • Send less keys than expected (Only table):

py6

**
I hope the content is useful for everyone. Thanks a lot!
Cheers!**

Cristian Carballo
cristian.carballo3@gmail.com

Top comments (0)