使用FastAPI创建标头

huangapple go评论63阅读模式
英文:

Headers with FastAPI

问题

我创建了一个需要用户代理的端点,正如文档中描述的那样:

然而,生成的 Swagger 文档将其显示为查询参数。

有任何想法我的设置有什么问题吗?

from typing import Annotated

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(user_agent: Annotated[str | None, Header()] = None):
    return {"User-Agent": user_agent}

我正在使用 Python 3.10 运行它。

英文:

I created an endpoint which requires the User Agent as described in the documentation:
https://fastapi.tiangolo.com/tutorial/header-params/#__tabbed_2_1

However, the Swagger documentation generated displays it as a query param.

使用FastAPI创建标头

Any ideas of what is wrong in my setup?

from typing import Annotated

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(user_agent: Annotated[str | None, Header()] = None):
    return {"User-Agent": user_agent}

I am running it with Python 3.10.

答案1

得分: 2

您运行的 fastapi 版本是多少?我在运行 fastapi 0.94.1 时遇到了相同的问题。

基本上,fastapi <0.95 不支持 Annotated。它会将 Annotated 解释为查询参数。问题是:它不会抛出错误,因为它仍然是有效的。

您有两个选择:将 fastapi 升级到 >=0.95 或使用未注释版本

@app.get("/items/")
async def read_items(user_agent: str | None = Header(default=None)):
    return {"User-Agent": user_agent}
英文:

What version of fastapi are you running? I found the same issue when running fastapi 0.94.1

Basically, fastapi <0.95 does not support Annotated. It will always interpret Annotated as a query parameter. The problem is: it won't throw an error because it is still valid.

You have two options: upgrade fastapi to >=0.95 or use the non-annotated version

@app.get(&quot;/items/&quot;)
async def read_items(user_agent: str | None = Header(default=None)):
    return {&quot;User-Agent&quot;: user_agent}

huangapple
  • 本文由 发表于 2023年3月20日 22:59:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75791918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定