The below schema can be converted to dict using branch.__dict__
branch = BranchIn(name='jfslkjf', regionId='fdfasd')
branchDict = branch.__dict__
branchDict = {'name': 'jfslkjf', 'regionId': 'fdfasd' }
How can i convert the dict object to schema again in FastAPI
You can use double asterisk ** for unpacking the multiple variables to turn to a single object
class Branch(BaseModel):
name: str
regionID: str
def check_type(obj):
return f"{obj} \n type: {type(obj)}"
I created this class and type checker, then i created the branch object
branch = Branch(name='jfslkjf', regionID='fdfasd')
check_type(branch)
Out: name='jfslkjf' regionID='fdfasd'
type: <class '__main__.Branch'>
Then i converted to a dict
branch_dict = branch.__dict__
check_type(branch_dict)
Out: {'name': 'jfslkjf', 'regionID': 'fdfasd'}
type: <class 'dict'>
So on i used double asteriks to unpack it
test_branch = Branch(**branch_dict)
check_type(test_branch)
Out: name='jfslkjf' regionID='fdfasd'
type: <class '__main__.Branch'>
You can simply spread the dict back into the Branch.
branchDict = {'name': 'jfslkjf', 'regionId': 'fdfasd' }
branchObj = Branch(**branchDict)
Fastapi uses pydantic.