Reputation: 83
I use FastAPi and Pydantic to model the requests and responses to an POST API.
I defined three class:
from pydantic import BaseModel, Field
from typing import List, Optional, Dict
class RolesSchema(BaseModel):
roles_id: List[str]
class HRSchema(BaseModel):
pk: int
user_id: str
worker_id: str
worker_name: str
worker_email: str
schedulable: bool
roles: RolesSchema
state: dict
class CreateHR(BaseModel):
user_id: str
worker_id: str
worker_name: str
worker_email: str
schedulable: bool
roles: RolesSchema
And My API's program:
@router.post("/humanResource", response_model=HRSchema)
async def create_humanResource(create: CreateHR):
query = HumanResourceModel.insert().values(
user_id=create.user_id,
worker_id=create.worker_id,
worker_name=create.worker_name,
worker_email=create.worker_email,
schedulable=create.schedulable,
roles=create.roles
)
last_record_id = await database.execute(query)
return {"status": "Successfully Created!"}
Input data format is json:
{
"user_id": "123",
"worker_id": "010",
"worker_name": "Amos",
"worker_email": "[email protected]",
"schedulable": true,
"roles": {"roles_id": ["001"]}
}
When I executed, I got TypeError: Object of type RolesSchema is not JSON serializable.
How can I fix the program to normal operation?
Upvotes: 8
Views: 7946
Reputation: 6147
If someone came here with the error message.
In my case:
data = MyBaseModel(**data)
# bad - TypeError: Object of type is not JSON serializable
json.dumps(data)
# good
data.json()
Upvotes: 4
Reputation: 32233
Try to use roles=create.roles.dict()
for creating query
instead of roles=create.roles
Upvotes: 1