8

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?

alex_noname
  • 26,459
  • 5
  • 69
  • 86
ppoozine
  • 83
  • 2
  • 7
  • Does this answer your question? [How to specify the response\_model in FastAPI on a non-default return?](https://stackoverflow.com/questions/73132238/how-to-specify-the-response-model-in-fastapi-on-a-non-default-return) – Chris Nov 26 '22 at 18:00
  • See related answers [here](https://stackoverflow.com/a/73974946/17865804) and [here](https://stackoverflow.com/a/74333692/17865804). – Chris Nov 26 '22 at 18:01

2 Answers2

4

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()
kujiy
  • 5,833
  • 1
  • 29
  • 35
  • In my case I did load the json of the object and then converted back to an object.... `raise HTTPException(status_code=404, detail=json.loads(resp.json()))` – Marcello DeSales Mar 30 '22 at 02:14
1

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

alex_noname
  • 26,459
  • 5
  • 69
  • 86