How to restrict content-type in fastapi request header?

Member

by jasen , in category: Third Party Scripts , 12 days ago

How to restrict content-type in fastapi request header?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 11 days ago

@jasen 

In FastAPI, you can restrict the Content-Type by using the Dependency Injection system. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from fastapi import FastAPI, Header, HTTPException, Depends

app = FastAPI()

def validate_content_type(content_type: str = Header(...)):
    allowed_content_types = ["application/json", "application/xml"]
    
    if content_type not in allowed_content_types:
        raise HTTPException(status_code=415, detail="Unsupported Media Type")
    
    return content_type

@app.post("/items/")
async def create_item(content_type: str = Depends(validate_content_type)):
    return {"content_type": content_type}


In this example, the validate_content_type function is a dependency that checks if the Content-Type header in the request is allowed or not. If the Content-Type is not in the list of allowed content types, it will raise an HTTPException with a status code of 415 (Unsupported Media Type).


You can then apply this dependency to the routes that you want to restrict the Content-Type by using the Depends function. In the create_item route, the content_type parameter is passed through the validate_content_type dependency, which ensures that the Content-Type header is allowed before the request is processed.