首页 > 解决方案 > 如果 URL 中有斜杠,FastAPI 不会在标头中包含 JSON 内容类型

问题描述

根据我的 URL 中是否有斜杠,FastAPI(使用 uvicorn 服务器)将省略content type: application/json标题。我担心客户可能会无意中在其 URL 中添加斜杠,然后无法返回 JSON 响应,所以我想知道

a)这是正确的行为吗?

b)我如何在服务器端处理它?

这是一个非常简单的 FastAPI 应用程序:

from fastapi import FastAPI
app = FastAPI()

app.get("/alist")
async def alist():
    somelist = [1, 2, 3, 4, 5]
    return somelist

现在这里是“正确”请求的标头的样子,即没有尾部斜杠的标头:

在此处输入图像描述

因为带有斜杠,所以缺少 content-type: application/json,这可能会使客户端感到困惑。

在此处输入图像描述

所以根据我上面的问题,这正常吗?我该怎么做才能防止客户期望 JSON 响应但无意中添加了尾部斜杠的错误?

标签: apifastapi

解决方案


a) 这是正确的行为吗?

  • 由于重定向(HTTP 状态代码 307)而出现此行为。
  • 我认为这应该自动处理。
  • 所以我认为我们应该在FastAPI repo 中打开一个新问题。

b)我如何在服务器端处理它?

有许多不同的解决方案:

1 - 通过使用一个关键技巧(简单解决方案)将列表转换为字典:

from fastapi import FastAPI
app = FastAPI()

app.get("/alist")
async def alist():
    somelist = [1, 2, 3, 4, 5]
    return {"numbers": somelist}


2 - 通过手动添加“内容类型”标题:

使用响应:

from fastapi import FastAPI, Response

app = FastAPI()

app.get("/alist")
async def alist(response: Response):
    # set content-type header to application/json
    response.headers["content-type"] = "application/json"
    somelist = [1, 2, 3, 4, 5]
    return somelist

使用 JSONResponse :

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

app.get("/alist")
async def alist():
    somelist = [1, 2, 3, 4, 5]
    # you can add additional headers
    headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
    # json response will enforce "content-type" header to be "application/json"
    return JSONResponse(content=somelist, headers=headers)


您可以在以下位置阅读有关 FastAPI 响应和标头的更多信息https://fastapi.tiangolo.com/advanced/response-headers/


推荐阅读