FASTAPI系列 14-使用JSONResponse 返回JSON内容

本文介绍了如何在FastAPI中使用JSONResponse返回JSON内容,包括默认格式、自定义状态码、headers和media_type。重点讲解了jsonable_encoder的作用及其在处理复杂数据类型时的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FASTAPI系列 14-使用JSONResponse 返回JSON内容



前言

当你创建一个 FastAPI 接口时,可以正常返回以下任意一种数据:dict,list,Pydantic 模型,数据库模型等等。FastAPI 默认会使用 jsonable_encoder 将这些类型的返回值转换成 JSON 格式,默认情况下会以content-type: application/json 格式返回。

在有些情况下,我们需要在路径操作中直接返回Response对象,这样我们能有更多的操作灵活性,比如自定义头headers 信息、自定义Cookie信息等


提示:以下是本篇文章正文内容,下面案例可供参考

一、默认返回的JSON格式

定义一个字典类型,然后fastpai会默认转化成json然后返回

from fastapi import FastAPI
import uvicorn

app = FastAPI()


@app.get('/users')
def users():
    user = {
        "user_name": "Teacher Li",
        "email": "Teacher_Li@qq.com"
    }
    return user

当使用get请求时,返回的格式:

HTTP/1.1 200 OK
date: Tue, 25 Mar 2023 10:40:41 GMT
server: uvicorn
content-length: 36
content-type: application/json

{"user_name": "Teacher Li","email": "Teacher_Li@qq.com"}

二、JSONResponse 自定义返回

可以使用 from starlette.responses import JSONResponse 定制返回内容,包含响应状态码,响应headers 和 响应body;
JSONResponse 继承自 Response 类,部分源码如下:

class JSONResponse(Response):  
    media_type = "application/json"  
  
    def __init__(  
        self,  
        content: typing.Any,  
        status_code: int = 200,  
        headers: typing.Optional[typing.Dict[str, str]] = None,  
        media_type: typing.Optional[str] = None,  
        background: typing.Optional[BackgroundTask] = None,  
    ) -> None:  
        super().__init__(content, status_code, headers, media_type, background)

JSONResponse可传参数:

  • content: 响应body内容,str 或者 bytes.
  • status_code: 响应状态码,int类型,默认200.
  • headers: 响应头部,dict类型.
  • media_type:media type. 例如"text/html".
  • background:后台任务

自定义 JSONResponse 响应, status_code 可以自定义状态码,FastAPI 会自动包含 Content-Length,以及Content-Type,charset等头信息。

from fastapi import FastAPI, status
from fastapi.responses import JSONResponse
import uvicorn

app = FastAPI()


@app.get('/users')
def users():
    user = {"user_name": "Teacher Li","email": "Teacher_Li@qq.com"}
    return JSONResponse(
        content=user, status_code=status.HTTP_200_OK
    )

当使用get请求时,返回的格式:

HTTP/1.1 200 OK
date: Tue, 25 Mar 2023 10:40:41 GMT
server: uvicorn
content-length: 36
content-type: application/json

{"user_name": "Teacher Li","email": "Teacher_Li@qq.com"}

三、自定义返回 headers 和 media_type

响应头部添加 headers 内容和设置 media_type 响应 body 媒体类型

@app.get('/resp/users')
async def users():
    user = {"user_name": "Teacher Li", "email": "Teacher_Li@qq.com"}
    return JSONResponse(
        content=user,
        status_code=status.HTTP_201_CREATED,
        headers={"x-token": "abcdefghijklmnop"},
        media_type="text/html"
    )

当使用get请求时,返回的格式:

HTTP/1.1 201 Created
date: Tue, 25 Mar 2023 10:40:41 GMT
server: uvicorn
x-token: abcdefghijklmnop
content-length: 36
content-type: text/html

{"user_name": "Teacher Li","email": "Teacher_Li@qq.com"}


总结

jsonable_encoder 是 FastAPI(一个用于构建高性能 Web 应用的现代、异步 Python 框架)中的一个实用函数,其主要功能是对 Pydantic 模型或任何其他可迭代对象进行编码,使其转换为可以安全地序列化为 JSON 的格式。

该函数会遍历对象的所有属性,并对其中的复杂数据类型如 datetime、UUID 等进行特殊处理,确保它们能够被 JSON 序列化引擎识别和正确处理。例如,datetime 对象会被转换为 ISO8601 格式的字符串,而 UUID 对象则通常会转换为字符串形式。

使用 jsonable_encoder 可以确保你在将数据返回给前端或者存入数据库时,不会因为数据类型的复杂性而出现问题。这极大地方便了开发者处理 API 返回的数据结构,提高了开发效率。

总结来说,jsonable_encoder 在 FastAPI 中的作用是提供一种便捷的方法,将符合 Pydantic 模型或其他特定类型的数据结构转换成适合 JSON 序列化的格式。

### 如何在 FastAPI返回 JSON 响应 为了确保 FastAPI 返回有效的 JSON 响应,可以利用 `fastapi` 库中的内置支持来处理 JSON 数据。当定义路径操作函数并指定其返回值时,FastAPI 自动会将其转换成 JSON 格式的 HTTP 响应。 对于简单的场景,在 Python 函数中直接返回字典或列表即可: ```python from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} ``` 上述代码展示了最基础的方式创建一个接收参数并返回 JSON 对象的接口[^1]。 如果需要更复杂的结构或是自定义状态码、头部信息等,则可以通过 `ResponseModel` 或者显式地使用 `JSONResponse` 类来进行控制: ```python from fastapi import FastAPI, Response from fastapi.responses import JSONResponse from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None app = FastAPI() @app.post("/items/", response_model=Item) async def create_item(item: Item): json_compatible_item_data = item.dict() return JSONResponse(content=json_compatible_item_data) @app.put("/items/{item_id}", status_code=200) async def update_item(item_id: int, item: Item): updated_item = {"id": item_id, **item.dict()} headers = {"X-Custom-Header": "CustomValue"} return JSONResponse(status_code=200, content=updated_item, headers=headers) ``` 这段例子说明了怎样通过 Pydantic 模型验证输入的数据,并且显示了如何设置特定的状态码以及额外的HTTP头字段。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值