如何在FastAPI中通过Pydantic简便实现多层嵌套JSON输出?
实现嵌套响应结构的两种简便方案
方案1:直接构造返回结构(适合少量接口场景)
无需额外定义新的Pydantic模型,直接在路径函数中将Article实例套入目标嵌套结构,同时给路径操作的response_model参数指定对应的嵌套类型即可:
from fastapi import FastAPI from typing import Dict app = FastAPI() # 你原有定义的Article模型保持不变 @app.get("/articles/{article_id}", response_model=Dict[str, Dict[str, Article]]) def get_article(article_id: int): # 这里是你查询得到的Article实例(ORM对象或Pydantic对象均可) article = Article(id=1, headline="a headline", text="a text", author_id=1) return {"data": {"article": article}}
这种方式完全没有冗余代码,适合只有个别接口需要该嵌套包装格式的场景。
方案2:定义通用泛型包装模型(适合全项目统一返回格式场景)
如果你的项目所有接口都需要统一用data+资源名的嵌套格式返回,可以一次性定义通用的泛型包装模型,所有资源类型都可以复用,不需要为每个资源单独写两层模型:
from typing import Generic, TypeVar from pydantic.generics import GenericModel T = TypeVar('T') # 通用外层data包装层 class DataResponse(GenericModel, Generic[T]): data: T # 通用内层资源包装层 class ResourceWrap(GenericModel, Generic[T]): __root__: Dict[str, T] # 调用时直接嵌套泛型即可,无需新增模型定义 @app.get("/articles/{article_id}", response_model=DataResponse[ResourceWrap[Article]]) def get_article(article_id: int): article = Article(id=1, headline="a headline", text="a text", author_id=1) return {"data": {"article": article}}
如果你所有接口的内层键名固定为对应资源的小写类名,还可以对通用模型做进一步封装,简化调用时的写法,一次定义全项目通用。
内容的提问来源于stack exchange,提问作者user3807965
相关产品推荐
相关产品推荐

