如何在 FastAPI 请求 header 中限制 content-type

How to restrict content-type in FastAPI request header

我是 FastAPI 框架的新手,我想用“application/vnd.api+[=20 来限制我的请求 header 内容类型=]", 但我无法找到一种方法来使用 Fast API 路由实例配置我的内容类型。

任何信息都会非常有用。

每个请求的 headers 中都有 content-type。你可以这样检查:

import uvicorn
from fastapi import FastAPI, HTTPException
from starlette import status

from starlette.requests import Request

app = FastAPI()


@app.get("/hello")
async def hello(request: Request):
    content_type = request.headers.get("content-type", None)
    if content_type != "application/vnd.api+json":
        raise HTTPException(
            status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
            detail=f"Unsupported media type {content_type}")

    return {"content-type": content_type}


if __name__ == '__main__':
    uvicorn.run("main", host="127.0.0.1", port=8080)

希望对您有所帮助

更好的方法是声明依赖:

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}

因此可以在需要时重复使用。

对于成功的请求,它将return像这样:

{
    "result": "All is OK!",
    "q": "Some query"
}

对于像这样不成功的事情:

{
    "detail": "Unsupported media type: type/unknown-type. It must be application/vnd.api+json"
}