简体   繁体   English

如何在 FastAPI 请求 header 中限制内容类型

[英]How to restrict content-type in FastAPI request header

I'm quite new to the FastAPI framework, I want to restrict my request header content type with "application/vnd.api+json", But I can't able to find a way to configure my content type with the Fast API route instance.我对 FastAPI 框架很陌生,我想用“application/vnd.api+json”限制我的请求 header 内容类型,但我无法找到使用快速 API 路由配置我的内容类型的方法实例。

Any info will be really useful.任何信息都会非常有用。

Each request has the content-type in its headers.每个请求的标头中都有content-type You could check it like so:你可以像这样检查它:

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)

Hope that helps希望有帮助

A better approach is to declare dependency:更好的方法是声明依赖:

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}

So it can be reused if needed.因此,如果需要,它可以重复使用。

For successful request it'll return something like this:对于成功的请求,它将返回如下内容:

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

And for unsuccessful something like this:对于这样的不成功的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM