DEV Community

M.T.Ramkrushna
M.T.Ramkrushna

Posted on

Pydantic Explained Simply: The Security Guard of Your API

One of the biggest beginner mistakes in backend development is trusting user input.

Users can send:

{
  "name": 123,
  "email": false,
  "age": "banana"
}
Enter fullscreen mode Exit fullscreen mode

Your application expects:

{
  "name": "John",
  "email": "john@gmail.com",
  "age": 25
}
Enter fullscreen mode Exit fullscreen mode

How do we stop bad data?

Enter Pydantic.


Think of an Airport Security Check

Before passengers board a plane:

  • Identity checked
  • Bags checked
  • Documents checked

Not because passengers are bad.

Because systems fail when validation is skipped.

Pydantic does the same for APIs.


Without Pydantic

data = request.json()

name = data["name"]
age = data["age"]
Enter fullscreen mode Exit fullscreen mode

What if:

{
  "age": "hello"
}
Enter fullscreen mode Exit fullscreen mode

Crash.


With Pydantic

from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int
Enter fullscreen mode Exit fullscreen mode

Input:

User(
    name="John",
    age=25
)
Enter fullscreen mode Exit fullscreen mode

Works.

Input:

User(
    name="John",
    age="hello"
)
Enter fullscreen mode Exit fullscreen mode

Validation error.


Why FastAPI Loves Pydantic

FastAPI automatically:

  • Validates requests
  • Generates documentation
  • Creates schemas
  • Returns useful errors

Example:

from fastapi import FastAPI

app = FastAPI()

@app.post("/users")
async def create_user(user: User):
    return user
Enter fullscreen mode Exit fullscreen mode

That's all.

Validation included.


Real Business Example

Imagine a payment API.

You expect:

amount: float
Enter fullscreen mode Exit fullscreen mode

User sends:

{
  "amount": "one million"
}
Enter fullscreen mode Exit fullscreen mode

Without validation:

  • Database corruption
  • Failed transactions
  • Production incidents

With Pydantic:

Request rejected instantly.


Hidden Superpower

Pydantic can transform data.

Input:

{
  "age": "25"
}
Enter fullscreen mode Exit fullscreen mode

Model:

class User(BaseModel):
    age: int
Enter fullscreen mode Exit fullscreen mode

Output:

age = 25
Enter fullscreen mode Exit fullscreen mode

Automatic conversion.

Magic with safety.


Think of Pydantic Like This

Database = Vault

API = Front Door

Pydantic = Security Guard

Without a guard, anyone walks in.

With a guard, only valid data enters.

That's why nearly every serious FastAPI project uses Pydantic.

Top comments (0)