[Python] Optional fields defaulting to "string" or 0.0 instead of null in Swagger UI

Discussão em 'Python' iniciado por Stack, Julho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using FastAPI with Pydantic's BaseModel, and I'm trying to define optional fields with a default value of None. However, in the Swagger UI (auto-generated docs), FastAPI shows "string" for optional str fields and 0.0 for optional float fields instead of showing null.

    The problem is that if users send these default placeholder values (like "string" or 0.0), they get stored in my database, instead of being stored as null (i.e., Python's None). This leads to incorrect data being saved.

    Here's an example of what I tried:

    from typing import Optional
    from pydantic import BaseModel, Field

    class MyModel(BaseModel):
    factory_id: Optional[str] = Field(default=None)
    price: Optional[float] = Field(default=None)


    I also tried:

    factory_id: Optional[str] = Field(default=None, example=None)


    But in both cases, Swagger UI still shows:

    {
    "factory_id": "string",
    "price": 0.0
    }


    How can I make Swagger UI show null instead of "string" or 0.0 for optional fields? Is there a way to override Swagger’s default example behavior globally or per field?

    Or do I need to enforce validation to reject placeholder values like "string"?

    Continue reading...

Compartilhe esta Página