Mahima Kulkarni
Mahima Kulkarni

Reputation: 137

How to write multiple response BaseModel in FastAPI?

I want to display multiple response model, so I have defined responses in a file and importing it to main file as below

@app.post("/mask", responses=Example_Mask)

in my response.py I have defined Example_Mask as

class Example_Mask(BaseModel):

    class Config:
        schema_extra = {
            "example": {
                "200": {"model": Example_200_Mask},
                "422": {"model": Example_422_Mask},
                "500": {"model": Example_500},
                "504": {"model": Example_504}
            }
        }

I have defined all Example models in the same way, but I am getting

TypeError: 'ModelMetaclass' object is not a mapping

error. Can you pls tel me where is this wrong?

Upvotes: 2

Views: 3041

Answers (1)

fchancel
fchancel

Reputation: 2699

What you currently pass to responses is not something that can be mapped. You are currently passing it an Object (class Example_Mask (BaseModel)).

To work response, needs values that it can map to, namely, your schema_extra from Config if you remove the example key

So to work you can do this:

class Example_Mask(BaseModel):

    class Config:
        schema_extra = {
                "200": {"model": Example_200_Mask},
                "422": {"model": Example_422_Mask},
                "500": {"model": Example_500},
                "504": {"model": Example_504}
        }

@app.post("/mask", responses=Example_Mask.Config.schema_extra)

Or you can just pass a dictionary, out of class:

responses = {
   "200": {"model": Example_200_Mask},
   "422": {"model": Example_422_Mask},
   "500": {"model": Example_500},
   "504": {"model": Example_504}
}

@app.post("/mask", responses=responses)

I'm not a FastAPI expert, so I can't assure this is the most consistent way, but anyway it works.

Upvotes: 1

Related Questions