[Python] How to exclude Optional unset values from a Pydantic model using FastAPI?

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have this model:

    class Text(BaseModel):
    id: str
    text: str = None


    class TextsRequest(BaseModel):
    data: list[Text]
    n_processes: Union[int, None]


    So, I want to be able to take requests like:

    {"data": ["id": "1", "text": "The text 1"], "n_processes": 8}


    and

    {"data": ["id": "1", "text": "The text 1"]}.


    Right now, in the second case I get:

    {'data': [{'id': '1', 'text': 'The text 1'}], 'n_processes': None}


    using this code:

    app = FastAPI()

    @app.post("/make_post/", response_model_exclude_none=True)
    async def create_graph(request: TextsRequest):
    input_data = jsonable_encoder(request)


    So how can I exclude n_processes here?

    Continue reading...

Compartilhe esta Página