example in schema extra is ignored by pydantic in fastapi

2 min read 05-10-2024
example in schema extra is ignored by pydantic in fastapi


Why Your schema_extra Is Getting Ignored in FastAPI: A Pydantic Mystery Solved

Scenario: You're building a beautiful API using FastAPI, and you're keen on providing your users with well-structured documentation. You've added the schema_extra field to your Pydantic models to include a description for each field. However, when you run your API, you find that your meticulously crafted descriptions are mysteriously absent.

The culprit: This is a common issue in FastAPI, and it often stems from the way Pydantic handles schema generation. While schema_extra is a fantastic tool for adding metadata, it's not automatically integrated into the final OpenAPI schema by default.

Here's an example:

from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class User(BaseModel):
    id: int
    name: str
    email: str

    schema_extra = {
        "example": {
            "id": 1,
            "name": "John Doe",
            "email": "[email protected]"
        }
    }

@app.get("/users")
async def get_users():
    return [
        User(id=1, name="Alice", email="[email protected]"),
        User(id=2, name="Bob", email="[email protected]")
    ]

In this code, we've defined a User model with schema_extra providing an example user. However, when you access the API documentation, you won't find this example in the schema.

The solution:

To make schema_extra work its magic, you need to use the extra argument in your get_users route function.

from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class User(BaseModel):
    id: int
    name: str
    email: str

    schema_extra = {
        "example": {
            "id": 1,
            "name": "John Doe",
            "email": "[email protected]"
        }
    }

@app.get("/users", response_model=list[User], response_model_include={"example"})
async def get_users():
    return [
        User(id=1, name="Alice", email="[email protected]"),
        User(id=2, name="Bob", email="[email protected]")
    ]

By adding response_model_include={"example"}, we explicitly tell FastAPI to include the example from schema_extra in the generated OpenAPI schema.

Important notes:

  • The schema_extra field can contain more than just an example. You can add descriptions, additional documentation, and other information about your models.
  • Using response_model_include is necessary for any route where you want to include the schema_extra information.

Benefits of using schema_extra:

  • Improved documentation: Provides clear examples and descriptions for your API endpoints.
  • Enhanced user experience: Helps developers understand the structure and functionality of your API more effectively.
  • Simplified integration: Reduces the need for external documentation, keeping your API documentation centralized.

Further exploration:

Remember: Providing clear and informative documentation is essential for building successful APIs. By leveraging schema_extra and other tools provided by FastAPI and Pydantic, you can create documentation that is both useful and user-friendly.