前言
响应模型我认为最主要的作用就是在自动化文档的显示时,可以直接给查看文档的小伙伴显示返回的数据格式。对于后端开发的伙伴来说,其编码的实际意义不大,但是为了可以不用再额外的提供文档,我们只需要添加一个 response_model=xxx,还是很爽的
示例
没有响应模型
from fastapi import FastAPI, Header
from pydantic import BaseModel
app = FastAPI()
class Resp(BaseModel):
code: int
msg: str
data: list
@app.get("/")
async def read_root():
return Resp(code=0, msg='success', data=[{
"name": "Python"}, {
"name": "Java"}])
效果

此时我们的文档只可以看到返回的是字符串,这和没写文档一样,现在尝试加上response_model
添加响应模型
from fastapi import FastAPI, Header
from pydantic import BaseModel
app = FastAPI(

最低0.47元/天 解锁文章
597

被折叠的 条评论
为什么被折叠?



