首页 > 解决方案 > Fastapi 和 Pydantic 构建 POST API:TypeError: Object of type is not JSON serializable

问题描述

我对 FastAPI 和 Pydantic 有疑问。

我想建立一个post api,程序显示这个:

@router.post('/productRoute', response_model=SuccessCreate, status_code=status.HTTP_201_CREATED)
async def create_product_route(create: CreatePR):
    query = ProductRouteModel.insert().values(
        user_id=create.user_id,
        route_id=create.route_id,
        route_name=create.route_name,
        head=create.head.dict(),
        body=create.body,
        route=create.route
    )
    await database.execute(query)
    return {"status": "Successfully Created!"}

这是 Pydantic 类:

class RouteSchema(BaseModel):
    id: str
    next: Optional[List[str]]
    prev: List[str]


class HeadSchema(BaseModel):
    b1: str
    b2: str
    b3: str


class BodySchema(BaseModel):
    a1: Optional[str]
    a2: Optional[str]


class CreatePR(BaseModel):
    user_id: str
    route_id: str
    route_name: str
    head: HeadSchema
    body: List[BodySchema]
    route: List[RouteSchema]

最后,我要发布的参数格式:

{
    user_id: "test1",
    route_id: "route_1",
    route_name: "route_name",
    head: {...},
    body: [{...}, {...}, ..., {...}],
    route: [{...}, {...}, ..., {...}]
}

当我执行时,我得到 TypeError: Object of type BodySchema is not JSON serializable。

如何将程序修复为正常运行?

标签: fastapipydantic

解决方案


您的代码似乎没问题。我不会发表强烈的声明,但我认为您的帖子正文是错误的。您能否验证您的JSON格式是否正确。您可以使用在线 JSON 编辑器进行检查(例如:https ://jsonbeautifier.org/ )。可能的错误可能是使用单引号、缺少/多余的逗号,甚至可能您忘记在键上加上引号。


推荐阅读