我对 FastAPI 框架相当陌生,我想用“application/vnd.api+json”限制我的请求标头内容类型,但我无法找到使用 Fast API 路由配置我的内容类型的方法实例。
任何信息都会非常有用。
小智 7
更好的方法是声明依赖:
from fastapi import FastAPI, HTTPException, status, Header, Depends
app = FastAPI()
def application_vnd(content_type: str = Header(...)):
"""Require request MIME-type to be application/vnd.api+json"""
if content_type != "application/vnd.api+json":
raise HTTPException(
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
f"Unsupported media type: {content_type}."
" It must be application/vnd.api+json",
)
@app.post("/some-path", dependencies=[Depends(application_vnd)])
def some_path(q: str = None):
return {"result": "All is OK!", "q": q}
Run Code Online (Sandbox Code Playgroud)
因此,如果需要的话可以重复使用。
对于成功的请求,它将返回如下内容:
{
"result": "All is OK!",
"q": "Some query"
}
Run Code Online (Sandbox Code Playgroud)
对于这样不成功的事情:
{
"detail": "Unsupported media type: type/unknown-type. It must be application/vnd.api+json"
}
Run Code Online (Sandbox Code Playgroud)