简体   繁体   中英

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": "Amos@mail.com",
     "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?

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM