0
0
FastapiHow-ToBeginner · 4 min read

How to Use Pydantic Model in FastAPI: Simple Guide

In FastAPI, you use Pydantic models to define the shape and validation of data for request bodies and responses. You create a class inheriting from BaseModel and use it as a type hint in your path operation functions to automatically validate and parse JSON data.
📐

Syntax

To use a Pydantic model in FastAPI, define a class that inherits from BaseModel. Each attribute represents a field with a type. Then, use this model as a parameter type in your route function to receive and validate JSON data.

  • BaseModel: The base class from Pydantic for data models.
  • Attributes: Define fields with Python types like str, int, etc.
  • Type hint: Use the model class as a function parameter type to tell FastAPI to expect and validate that data.
python
from pydantic import BaseModel
from fastapi import FastAPI

class Item(BaseModel):
    name: str
    price: float

app = FastAPI()

@app.post("/items/")
async def create_item(item: Item):
    return item
💻

Example

This example shows a FastAPI app where a POST request to /items/ expects JSON data matching the Item model. FastAPI validates the data and returns it back.

python
from pydantic import BaseModel
from fastapi import FastAPI

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

app = FastAPI()

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

# To test, send POST request with JSON:
# {"name": "Book", "price": 12.99, "description": "A good book"}
Output
{"item_name": "Book", "item_price": 12.99, "item_description": "A good book"}
⚠️

Common Pitfalls

Common mistakes when using Pydantic models in FastAPI include:

  • Not inheriting from BaseModel, so validation won't work.
  • Using incorrect types or missing required fields in requests causes validation errors.
  • Forgetting to use the model as a type hint in the route function parameter.
  • Trying to use Pydantic models for query parameters instead of request bodies without proper setup.

Always check error messages from FastAPI to understand validation issues.

python
from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

# Wrong: Missing BaseModel inheritance
class WrongItem:
    name: str
    price: float

@app.post("/wrong-items/")
async def create_wrong_item(item: WrongItem):
    return item

# Correct:
class CorrectItem(BaseModel):
    name: str
    price: float

@app.post("/correct-items/")
async def create_correct_item(item: CorrectItem):
    return item
📊

Quick Reference

  • Define model: Create class inheriting BaseModel with typed fields.
  • Use in route: Add model as parameter type to get validated data.
  • Optional fields: Use field: type | None = None for optional data.
  • Validation errors: FastAPI returns clear error messages if data is invalid.

Key Takeaways

Use Pydantic models by inheriting from BaseModel to define data shapes in FastAPI.
Pass the model as a type hint in route functions to enable automatic validation and parsing.
Optional fields can be declared with a default None value using Python's union type syntax.
FastAPI returns detailed validation errors if the input data does not match the model.
Always inherit from BaseModel; otherwise, FastAPI won't validate the data.