0
0
FastAPIframework~3 mins

Why Example data in schema in FastAPI? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a tiny addition to your schema can make your API docs shine effortlessly!

The Scenario

Imagine you are building an API and want to show users what kind of data your endpoints expect or return. You try to write this example data manually in your documentation or comments.

The Problem

Manually writing example data is easy to get wrong, often outdated, and requires extra work every time your data model changes. This leads to confusing docs and frustrated users.

The Solution

FastAPI lets you add example data directly inside your schema definitions. This keeps examples accurate, up-to-date, and automatically shown in your API docs.

Before vs After
Before
"""User data: {
  'id': 1,
  'name': 'Alice'
}"""
After
class User(BaseModel):
    id: int
    name: str

    class Config:
        schema_extra = {
            "example": {"id": 1, "name": "Alice"}
        }
What It Enables

This makes your API self-explanatory and easier to use, saving time and avoiding mistakes.

Real Life Example

When a developer visits your API docs, they instantly see example user data, so they know exactly what to send or expect back.

Key Takeaways

Manual example data is error-prone and hard to maintain.

FastAPI schemas can include example data directly.

API docs become clearer and more reliable automatically.