How to respond on pydantic instantiation errors


This Content is from Stack Overflow. Question asked by feder

I receive signals …

from pydantic import BaseModel
class Signal(BaseModel):        
    provider_id: str
    sequence_id: Optional[int]

… on a fastapi endpoint. They perfectly map/deserialize the json into the class."/signal")
async def receive_signal(signal: Signal, tags=["signal"]):
   #do something

How do I respond with an error on that POST request IF the request omits a mandatory attribute of the signal? Let’s say the provider_id. What is the best practice and state of the art? (I would not know where to catch that exception because the deserialization happens before the code of the receive_signal method is invoked.)

I would like to return the following json:
{ “result”: “error”, “response”: “provider_id was not provided”}


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?