Reputation: 433
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.
Any info will be really useful.
Upvotes: 3
Views: 12690
Reputation: 180
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"
}
Upvotes: 8
Reputation: 1442
Each request has the content-type
in its headers. 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 🙂
Upvotes: 3