Skip to content

响应参数

6.1 Response响应

默认情况下,FastAPI会将路径操作函数返回的任何 Python 对象(包括字典、列表、Pydantic模型或 ORM 对象)通过内置的 jsonable_encoder 自动转换为 JSON 兼容格式,并封装在 JSONResponse 中发送

如果需要返回非 JSON 数据(如 HTML、文件流),FastAPI提供了丰富的响应类型来返回不同数据:

响应类型 用途 示例
JSONResponse 默认响应,返回JSON数据 return {"key": "value"}
HTMLResponse 返回HTML内容 return HTMLResponse(html_content)
PlainTextResponse 返回纯文本 return PlainTextResponse("text")
FileResponse 返回文件下载 return FileResponse(path)
StreamingResponse 流式响应 生成器函数返回数据
RedirectResponse 重定向 return RedirectResponse(url)

I. 默认返回

FastAPI 会自动将返回值转换为 JSON 响应(使用 JSONResponse):

main.py

1
2
3
@app.get("/default")
def read_root():
    return {"message": "Hello World"}

image-20251012090418841

II. HTML返回

导入HTMLResponse类,然后将html代码返回,浏览器会自动渲染html代码

main.py

1
2
3
4
5
from fastapi.responses import HTMLResponse

@app.get("/html", response_class=HTMLResponse)
def html_response():
    return "<h1>Hello FastAPI</h1>"

image-20251012090853950

III. 返回File文件

FileResponse 是 FastAPI 提供的专门用于 返回文件(如图片、PDF、Excel、音视频等)的响应类。

main.py

1
2
3
4
5
6
from fastapi.responses import FileResponse

@app.get("/file")
def download_file():
    file_path = "./files/example.pdf"
    return FileResponse(file_path)

image-20251012092051753

6.2 响应数据的构造与验证

response_model 是路径操作装饰器(如 @app.get@app.post)的关键参数,用于定义 API 响应的数据内容。它强制执行数据结构,提供输出验证,同时是实现数据安全性的重要机制 。

通过将 Pydantic 模型传递给 response_model,代码如下:

main.py

from pydantic import BaseModel

# 数据库模型
class News(BaseModel):
    id: int
    content: str

@app.get("/news/", response_model=News)
async def read_user_me():
    # 假设函数返回 News 实例
    new = News(id=1, content="这是一条新闻数据")
    # new对象会自动转为Json数据
    return new

image-20251012093459975


image-20251012093746529

6.3 指定返回状态码

可以在路径操作装饰器中设置 status_code 参数来覆盖默认状态码 :

1
2
3
@app.get("/code/", status_code=222)
async def get_code():
    return {"message": "code"}

image-20251012094210627

6.4 异常处理

对于客户端引发的错误(4xx,如资源未找到、认证失败),应使用 fastapi.HTTPException 来中断正常处理流程,并返回标准错误响应 。

  • 抛出异常:必须提供 HTTP status_code 和可选的 detail 消息 。

  • 自动响应:FastAPI 会自动捕获此异常,并生成一个标准的 JSON 格式错误响应,格式通常为 { "detail": "错误信息" }

    from fastapi import HTTPException
    
    @app.get("/news/{new_id}")
    async def read_news(new_id: int):
        FAKE_DB = [1,2,3,4,5,6]
        # 判断查询新闻id是否在数据库中
        if new_id not in FAKE_DB:
            # 如果资源不存在,抛出 404 错误
            raise HTTPException(status_code=404, detail="Item not found")
        return {"item": new_id}
    

    image-20251012094723554


image-20251012094841682