How to respond on pydantic instantiation errors

Viewed 34

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.

@router.post("/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"}

0 Answers
Related