When I use fastapi and pydantic to build POST API, appear a TypeError: Object of type is not JSON serializable
When I use fastapi and pydantic to build POST API, appear a TypeError: Object of type is not JSON serializable
我使用 FastAPI 和 Pydantic 来模拟对 POST API 的请求和响应。
我定义了三个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
我的API的程序:
@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!"}
输入数据格式为json:
{
"user_id": "123",
"worker_id": "010",
"worker_name": "Amos",
"worker_email": "Amos@mail.com",
"schedulable": true,
"roles": {"roles_id": ["001"]}
}
当我执行时,我得到 TypeError: Object of type RolesSchema is not JSON serializable.
如何修复程序才能正常运行?
尝试使用 roles=create.roles.dict()
创建 query
而不是 roles=create.roles
如果有人带着错误信息来到这里。
就我而言:
data = MyBaseModel(**data)
# bad - TypeError: Object of type is not JSON serializable
json.dumps(data)
# good
data.json()
我使用 FastAPI 和 Pydantic 来模拟对 POST API 的请求和响应。
我定义了三个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
我的API的程序:
@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!"}
输入数据格式为json:
{
"user_id": "123",
"worker_id": "010",
"worker_name": "Amos",
"worker_email": "Amos@mail.com",
"schedulable": true,
"roles": {"roles_id": ["001"]}
}
当我执行时,我得到 TypeError: Object of type RolesSchema is not JSON serializable.
如何修复程序才能正常运行?
尝试使用 roles=create.roles.dict()
创建 query
而不是 roles=create.roles
如果有人带着错误信息来到这里。
就我而言:
data = MyBaseModel(**data)
# bad - TypeError: Object of type is not JSON serializable
json.dumps(data)
# good
data.json()