英文:
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.
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("/items/")
async def read_items(user_agent: str | None = Header(default=None)):
return {"User-Agent": user_agent}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论