[Python] Make every field as optional with Pydantic

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm making an API with FastAPI and Pydantic.

    I would like to have some PATCH endpoints, where 1 or N fields of a record could be edited at once. Moreover, I would like the client to only pass the necessary fields in the payload.

    Example:

    class Item(BaseModel):
    name: str
    description: str
    price: float
    tax: float


    @app.post("/items", response_model=Item)
    async def post_item(item: Item):
    ...

    @app.patch("/items/{item_id}", response_model=Item)
    async def update_item(item_id: str, item: Item):
    ...


    In this example, for the POST request, I want every field to be required. However, in the PATCH endpoint, I don't mind if the payload only contains, for example, the description field. That's why I wish to have all fields as optional.

    Naive approach:

    class UpdateItem(BaseModel):
    name: Optional[str] = None
    description: Optional[str] = None
    price: Optional[float] = None
    tax: Optional[float]


    But that would be terrible in terms of code repetition.

    Any better option?

    Continue reading...

Compartilhe esta Página