FastAPI(46)- JSONResponse
背景
- 创建 FastAPI 路径操作函数时,通常可以从中返回任何数据:字典、列表、Pydantic 模型、数据库模型等
- 默认情况下,FastAPI 会使用 jsonable_encoder 自动将该返回值转换为 JSON 字符串
- 然后,FastAPI 会将与 JSON 兼容的数据(例如 dict)放在 JSONResponse 中,然后将 JSONResponse 返回给客户端
- 总结:默认情况下,FastAPI 将使用 JSONResponse 返回响应
- 但是可以直接从路径操作函数中返回自定义的 JSONResponse
返回响应数据的常见方式(基础版)
https://www.cnblogs.com/poloyy/p/15364635.html
最简单的栗子
路径操作函数返回一个 Pydantic Model
#!usr/bin/env python # -*- coding:utf-8 _*- """ # author: 小菠萝测试笔记 # blog: https://www.cnblogs.com/poloyy/ # time: 2021/10/3 3:26 下午 # file: 38_responses.py """ from typing import Optional import uvicorn from fastapi import FastAPI from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse from pydantic import BaseModel app = FastAPI() class Item(BaseModel): id: str name: str title: Optional[str] = None @app.post("/item") async def get_item(item: Item): # 打印看看传进来的数据是什么 print(item, type(item)) # 直接返回传进来的数据 return item if __name__ == '__main__': uvicorn.run(app="38_responses:app", reload=True, host="127.0.0.1", port=8080)
正常传参的请求结果
Response Header 的显示 content-type 是 JSON
console 打印结果
id='string' name='string' title='string' <class '38_responses.Item'> INFO: 127.0.0.1:51856 - "POST /item HTTP/1.1" 200 OK
- item 类型的确是 Pydantic Model 类
- 但最终返回给客户端的是一个 JSON 数据
等价写法
@app.post("/item") async def get_item(item: Item): return item
这样写也能返回 JSON 数据,是因为FastAPI 是自动帮忙做了转换的
等价写法如下
from fastapi.encoders import jsonable_encoder @app.post("/item") async def get_item(item: Item): json_body = jsonable_encoder(item) return JSONResponse(content=json_body)
打印数据,来看看细节
@app.post("/item2") async def get_item(item: Item): json_body = jsonable_encoder(item) print(json_body, type(json_body)) return JSONResponse(content=json_body)
console 打印结果
{'id': 'string', 'name': 'string', 'title': 'string'} <class 'dict'> INFO: 127.0.0.1:52880 - "POST /item2 HTTP/1.1" 200 OK
假设将 item Pydantic Model 类型直接传给 JSONResponse 呢?
@app.post("/item3") async def get_item(item: Item): return JSONResponse(content=item)
访问该接口就会报错
raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Item is not JSON serializable
- 类型错误:项目类型的对象不是 JSON 可序列化的
- 因为它无法转换为 JSON 数据,所以报错了
看看 JSONResponse 源码
会调用 json.dumps() 方法
看看 Response 源码
看到其实可以自定义 status_code、headers、media_type 哦
headers 后面再用单独的篇幅来讲
修改 status_code 响应码
@app.post("/item2") async def get_item(item: Item): json_item = jsonable_encoder(item) return JSONResponse(content=json_item, status_code=status.HTTP_201_CREATED)
正确传参的请求结果
更多自定义响应类型
- JSONResponse
- HTMLResponse、PlainTextResponse
- ORJSONResponse、UJSONResponse
- RedirectResponse
- StreamingResponse、FileResponse
标签:
FastAPI
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!