ppoozine
ppoozine

Reputation: 83

When I use fastapi and pydantic to build POST API, appear a TypeError: Object of type is not JSON serializable

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

Answers (2)

kujiy
kujiy

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

alex_noname
alex_noname

Reputation: 32233

Try to use roles=create.roles.dict() for creating query instead of roles=create.roles

Upvotes: 1

Related Questions