Handling Request Body and POST Requests in FastAPI with Pydantic Pre-Validators

Posted by


In this tutorial, we will cover how to work with FastAPI request bodies and perform POST requests using Pydantic pre-validators. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. Pydantic is a data validation library for Python, which plays a crucial role in FastAPI for serializing and validating request and response data.

In FastAPI, to handle incoming data sent as part of a POST request, you will need a request body model class that defines the structure of the incoming data. You will also need to define Pydantic models for request validation before the data is processed. Let’s go through a step-by-step guide on how to create a FastAPI application with request body models and Pydantic pre-validators.

Step 1: Install FastAPI and Pydantic
Before we start, ensure you have FastAPI and Pydantic installed. If not, you can install them using pip:

pip install fastapi
pip install uvicorn
pip install pydantic

Step 2: Create a FastAPI Application
Create a new Python file (e.g., main.py) and import the necessary modules:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

Initialize the FastAPI application:

app = FastAPI()

Step 3: Create a Request Body Model
Define a request body model using Pydantic that will represent the structure of the data expected in the POST request body:

class Item(BaseModel):
    name: str
    description: str = None
    price: float

Step 4: Create a POST Endpoint
Create a POST endpoint in FastAPI that will receive data in the request body and validate it against the Item model:

@app.post("/items/")
async def create_item(item: Item):
    return {"name": item.name, "price": item.price}

In this code snippet, we define a route /items/ that accepts POST requests. The create_item function takes an Item object as an argument, which will automatically validate the incoming request data against the defined model. If the data does not match the model’s structure, FastAPI will return a 422 Unprocessable Entity response with detailed validation errors.

Step 5: Start the FastAPI Application
Run the FastAPI application using Uvicorn:

uvicorn main:app --reload

Visit http://127.0.0.1:8000/docs on your browser to access the Swagger UI for testing the POST endpoint.

Step 6: Test the POST Endpoint
Using the Swagger UI or an API testing tool like Postman, send a POST request to http://127.0.0.1:8000/items/ with the following JSON payload:

{
  "name": "Sample Item",
  "price": 10.99
}

You should receive a successful response containing the name and price of the created item.

Step 7: Pydantic Pre-validators
Pydantic supports pre-validators that allow you to add custom validation logic to your model fields. For example, you can define a pre-validator that checks if the price of the item is greater than zero:

from pydantic import validator

class Item(BaseModel):
    name: str
    description: str = None
    price: float

    @validator("price")
    def price_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError("Price must be greater than zero")
        return v

With this pre-validator in place, any POST request containing a non-positive price value will be rejected, and an error message will be returned.

In this tutorial, you learned how to work with request bodies and perform POST requests in FastAPI using Pydantic pre-validators. By defining request body models and employing Pydantic for data validation, you can ensure that your APIs accept and process data reliably and securely.

0 0 votes
Article Rating

Leave a Reply

11 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@subz424
5 hours ago

app = FastAPI(swagger_ui_parameters={"tryItOutEnabled": True})

In case anyone wants to skip the step of tapping "Try It Out" every time and go straight to executing API calls in the docs page.

@hamzaelmhoujab2350
5 hours ago

Great video 🦾

@LucidProgramming
5 hours ago

You are an excellent teacher and have an equally great taste in music. Love the Aphex Twin and Boards of Canada references. Cheers!

@stevenwilson2292
5 hours ago

Will there be more in this series?

@victorajayi9056
5 hours ago

isn't validator deprecated in Pydantic v2?

@深夜酒吧
5 hours ago

did you edit your video after recording? or just one shot and upload?

@frameff9073
5 hours ago

good

@seydinaoumarsamabaly1806
5 hours ago

Thank you man for giving us our dose of week-end ! All clear.

@AmoahDevLabs
5 hours ago

Great as always. Thanks very much for your time.

@farzadmf
5 hours ago

Is it safe to call model_dump directly on what we receive from the request with no validation?

@photiosloupis4529
5 hours ago

Very clear and concise at a pace that that is welcomed. Looking forward to when you get to PostgreSQL integration with particular interest in working with Enums with PostgreSQL as well as relationships and link tables. Thank you for taking the time to make this series, I am really enjoying your content.

11
0
Would love your thoughts, please comment.x
()
x