How to handle multiple pydantic response in fast api
See original GitHub issueDescribe 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:
- Created 3 years ago
- Comments:10 (1 by maintainers)
Top GitHub Comments
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:
Thanks @Rushyanth111