FastAPI - Beginner to Pro / Project 2- Move Fast With FastAPI

Pydantic and Data Validation Overview

πŸ“¦ What Is Pydantic?

In FastAPI, Pydantic is a library that handles incoming data safely and correctly.

It is used for:

  • βœ… Data modeling

  • βœ… Data validation

  • βœ… Data parsing (type conversion)

  • βœ… Clear error messages

πŸ‘‰ Think of Pydantic as a data checker for your API.

Whenever data is sent to your API (e.g., POST request), Pydantic verifies that it is correct before your code uses it.


βš™οΈ What Pydantic Does

1️⃣ Validates Data

Ensures the data matches expected types and rules.

πŸ‘‰ Example: If rating must be 0–5, value 10 will be rejected.

2️⃣ Converts Data Automatically

Converts compatible values to the correct type.

Examples:

  • "5" β†’ 5

  • "true" β†’ True

3️⃣ Returns Clear Errors

If data is invalid, FastAPI returns a structured error instead of crashing.

4️⃣ Generates API Docs

Pydantic models help FastAPI automatically create documentation at:

  • /docs (Swagger UI)

πŸ‘‰ In short: Pydantic makes your API safe, reliable, and well-documented.


🧱 How We Implement Pydantic (Step-by-Step)

Here’s how we typically use Pydantic in a FastAPI project:

Step 1: Create a separate request model

Step 2: Inherit from BaseModel

Step 3: Add validation rules using Field

This keeps your API clean, organized, and secure.

πŸ§ͺ Example β€” Pydantic Request Data Validation

class BookRequest(BaseModel):
    id: int
    title: str = Field(min_length=3)
    author: str = Field(min_length=1)
    description: str = Field(min_length=1, max_length=100)
    rating: int = Field(gt=-1, lt=6)

Let’s break this down carefully πŸ‘‡

πŸ‘‰ BaseModel

  • BaseModel is the parent class from Pydantic.

  • By inheriting from it, your model automatically gains:

    • Data validation

    • Type conversion

    • Error handling

    • Serialization support

πŸ‘‰ Field(...)

The Field() function allows you to apply validation rules to each attribute.

Example:

  • min_length=3 β†’ String must have at least 3 characters

  • max_length=100 β†’ String must not exceed 100 characters

  • gt=-1 β†’ Greater than -1

  • lt=6 β†’ Less than 6

So:

rating: int = Field(gt=-1, lt=6) 
# πŸ‘‰ rating must strictly **between 0 and 5**

Means:

πŸ‘‰ Rating must be between 0 and 5

πŸ”Ž Important Keywords

Parameter

Meaning

gt

Greater than

lt

Less than

min_length

Minimum number of characters

max_length

Maximum number of characters

This ensures your API only accepts properly structured data.


πŸ” Converting BookRequest to Book

Now that we’ve validated the request data…

πŸ€” What happens next?

After validation succeeds, we convert the Pydantic model into a domain object.

πŸ€” Why?

Because:

  • BookRequest is for validation

  • Book is your actual application model

This separation keeps your architecture clean.


🧩 Example β€” Conversion in Action

@app.post("/create_book")
async def create_book(book_request: BookRequest): 
    new_book = Book(**book_request.model_dump())
    BOOKS.append(new_book)

Let’s go step-by-step πŸ‘‡

πŸ‘‰ Step 1: Receive Validated Data

book_request: BookRequest

FastAPI:

  • Automatically reads incoming JSON

  • Validates it using BookRequest

  • Rejects invalid data

  • Passes only valid data to the function

πŸ‘‰ Step 2: Convert to Dictionary

book_request.model_dump()

This converts the Pydantic object into a standard Python dictionary.

Example output:

{
    "id": 1,
    "title": "FastAPI Guide",
    "author": "Author 4",
    "description": "Beginner friendly guide",
    "rating": 5
}

πŸ‘‰ Step 3: Unpack Using *

Book(**book_request.model_dump())

The double asterisk **:

  • Unpacks key–value pairs

  • Passes them into the Book constructor

This creates a proper Book object.

πŸ‘‰ Step 4: Store the Object

BOOKS.append(new_book)

Now the validated and converted book is added to your data store.

βœ” Only clean

βœ” Only validated

βœ” Only structured data