0
0
FastapiHow-ToBeginner · 3 min read

How to Create Models in FastAPI: Simple Guide with Examples

In FastAPI, you create models by defining classes that inherit from pydantic.BaseModel. These models define the data structure and validation rules for request and response data in your API.
📐

Syntax

To create a model in FastAPI, define a class that inherits from pydantic.BaseModel. Inside the class, declare attributes with type annotations to specify the expected data fields and their types.

Each attribute represents a field in the model, and Pydantic automatically validates the data based on these types.

python
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None
💻

Example

This example shows a FastAPI app with a model Item. The model defines three fields: name (string), price (float), and an optional is_offer (boolean). The model is used to validate incoming JSON data in a POST request.

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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

@app.post("/items/")
async def create_item(item: Item):
    return {"item_name": item.name, "item_price": item.price, "item_offer": item.is_offer}
Output
When you send a POST request to /items/ with JSON {"name": "Book", "price": 12.5}, the response will be {"item_name": "Book", "item_price": 12.5, "item_offer": null}
⚠️

Common Pitfalls

  • Not inheriting from BaseModel will cause FastAPI to not validate the data.
  • Missing type annotations means fields won't be validated or included.
  • Using mutable default values like lists or dicts directly can cause unexpected behavior; use Field(default_factory=...) instead.
  • Confusing optional fields: use field: type = None or Optional[type] to mark fields as optional.
python
from pydantic import BaseModel

# Wrong: missing BaseModel inheritance
class WrongModel:
    name: str

# Correct
class CorrectModel(BaseModel):
    name: str

# Wrong: mutable default
from typing import List
class BadModel(BaseModel):
    tags: List[str] = []  # Avoid this

# Correct: use default_factory
from pydantic import Field
from typing import List
class GoodModel(BaseModel):
    tags: List[str] = Field(default_factory=list)
📊

Quick Reference

Remember these key points when creating models in FastAPI:

  • Always inherit from pydantic.BaseModel.
  • Use Python type hints to define fields.
  • Set default values for optional fields.
  • Use Field(default_factory=...) for mutable defaults.
  • Models are used for request validation and response serialization.

Key Takeaways

Create models by inheriting from pydantic.BaseModel and using type annotations.
Models validate and serialize data automatically in FastAPI endpoints.
Always define optional fields with default values or Optional types.
Avoid mutable default arguments; use Field with default_factory instead.
Models improve API reliability by enforcing data structure and types.