0
0
FastapiHow-ToBeginner · 4 min read

How to Create Request Body Model in FastAPI

In FastAPI, create a request body model by defining a class that inherits from pydantic.BaseModel. Use this model as a function parameter in your path operation to automatically parse and validate incoming JSON request bodies.
📐

Syntax

Define a request body model by creating a class that inherits from pydantic.BaseModel. Add attributes with types to specify the expected data fields. Use this model as a parameter in your FastAPI path operation function to receive and validate the request body.

  • class ModelName(BaseModel): - defines the data structure.
  • field_name: type - declares each expected field and its type.
  • def endpoint(model: ModelName): - uses the model to get validated data from the request body.
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
💻

Example

This example shows a FastAPI app with a request body model Item. When you send a POST request with JSON data matching the model, FastAPI parses and validates it automatically. The endpoint returns the same data as confirmation.

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, "offer": item.is_offer}

# To test, run this app and send a POST request to /items/ with JSON:
# {"name": "Book", "price": 12.99, "is_offer": true}
Output
POST /items/ with JSON {"name": "Book", "price": 12.99, "is_offer": true} returns { "item_name": "Book", "item_price": 12.99, "offer": true }
⚠️

Common Pitfalls

Common mistakes include:

  • Not inheriting from BaseModel, so FastAPI can't validate the data.
  • Forgetting to type annotate fields, which disables validation.
  • Using mutable default arguments instead of default values.
  • Not using the model as a function parameter, so request body is not parsed.

Always use BaseModel and proper type hints for reliable validation.

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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

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

# Right: inherits BaseModel
class CorrectItem(BaseModel):
    name: str
    price: float

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

Quick Reference

Tips for creating request body models in FastAPI:

  • Use pydantic.BaseModel to define models.
  • Type annotate all fields for validation.
  • Set default values for optional fields.
  • Use the model as a parameter in your endpoint function.
  • FastAPI automatically parses JSON request bodies into your model.

Key Takeaways

Define request body models by inheriting from pydantic.BaseModel with typed fields.
Use the model as a parameter in your FastAPI endpoint to get validated request data.
Always type annotate fields to enable automatic validation and parsing.
Set default values for optional fields to make them not required in requests.
Avoid missing BaseModel inheritance or type hints to prevent validation errors.