question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to handle multiple pydantic response in fast api

See original GitHub issue

Describe the bug

When using Union on response_model, it doesn’t return accurate result To Reproduce

Create three models

from pydantic import BaseModel

   class parent(BaseModel):
       id: str

   class child1(parent):
      code: str
      user: Any

  class child2(parent):
    `error:` Any

class child3(parent):
 code: str
 user_data: Any

Add it on response_model
     from typing import Union
    from fastapi import APIRouter

    router = APIRouter()

   @router.post('/verify', response_model=Union[child1, child3,child2])
   async def something(some: some):
      dict1 = {
          "id": 1,
          "code" : "213",
          "user":{'id':"123","pass":"pass"}
          }
      dict2 = {
          "id": 1,
          "error" : "213"
         }
       dict3 = {
          "id": 1,
          "code" : "213",
          "user_data":{'id':"123","pass":"pass"}
         }
       
     if cond1 :  
          return child1(**dict1).dict()
    elif cond2 :  
          return child2(**dict2).dict()
     else:
         return child3(**dict3).dict()

output actual :
On running all the condition one by one output that i got is not correct when cond 1 gets true then

      {
        "id": 1,
         "code" : "213",
         "user":{'id':"123","pass":"pass"}
        }

when cond 2 gets true then

{
       "id": 1,
        "error" : "213"
       }

when cond 3 gets true then

{
     "id": 1,
      "code" : "213"
     }

Expected behavior

cond 1 and 2 output are correct but cond3 is incorrect i want cond3 output to have user_data field as below

{
        "id": 1,
         "code" : "213"
       "user_data":{'id':"123","pass":"pass"}
        }

how can i get the output to have all the fields of dict3

i am new to fast api and can anyone help me with this issue, any resolution to this issue or any other way to get the expected output with schema in swagger UI

Additional Info: What i observed here is Field type: Any has issue , as when i specify the field to str or dict , it gives the correct output as expected

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:10 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
Rushyanth111commented, Aug 24, 2020

Currently, it is a known missing feature within the Swagger UI (See: #1083 ) and the generation of the example cannot be automatically done by Swagger UI, however it is possible to provide a manual example, which would mean that you have to make an example to be displayed.

Link to the Relevant Issue Solution from #1083

Link to Another Solution from #86

The Example Shows you that you need to provide a manual example like so:

Create A Class that holds the Union of any of the three Classes:


class parent(BaseModel):
    id: str


class child1(parent):
    code: str
    user: Dict[str, str]


class child2(parent):
    error: Any


class child3(parent):
    code: str
    user_data: Dict[str, str]


class UnionChild(BaseModel): # This will Hold the Union
    Child: Union[child1, child2, child3] #The Union Required

    class Config: #This is inside UnionChild, do not place it outside. 
        schema_extra = {
            "example": {                    #Mandatory field, this holds your example. Define Your Field from here. 
                "id": "1",
                "error": "Some Random String",
                "user": "OSAS UVUWE",
                "user_data": {"oh": "oh_no"},
            }
        }


app = FastAPI()


@app.get("/verify", response_model=UnionChild)
async def something(some: int):
    pass
2reactions
gunjeetgulatigitcommented, Aug 24, 2020
Read more comments on GitHub >

github_iconTop Results From Across the Web

Is there any way to have multiple response models in FastAPI ...
Yes this is possible. You can use Union for that in the response_model= parameter in your path decorator (I used the new python...
Read more >
Extra Models - FastAPI
You can declare a response to be the Union of two types, that means, that the response ... Use multiple Pydantic models and...
Read more >
Response Model - FastAPI
This can be used as a quick shortcut if you have only one Pydantic model and want to remove some data from the...
Read more >
Additional Responses in OpenAPI - FastAPI - tiangolo
FastAPI will keep the additional information from responses , and combine it with the JSON Schema from your model. For example, you can...
Read more >
Multiple Models with FastAPI - SQLModel - tiangolo
Review Creation Schema¶ · Review Response Schema¶ · Multiple Hero Schemas¶ · Multiple Models with Duplicated Fields¶ · Use Multiple Models to Create...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found