How to add custom headers to static files in fastapi


We are using the following method to mount the static files from a directory
app.mount("/static", StaticFiles(directory="static"), name="static")

We have sent a custom headers for api for security related steps using a common method before sending response to the client.

Is there a way to send the security headers to css/js/html static files the same kind of headers. ?

Just want to know, the way or approach to send custom headers to static files.

Asked By: sujata singh



Like this

from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

async def function(file_path: str):
    response = FileResponse(f"static/{file_path}")
    response.headers["X-Custom-Header"] = "Your custom header value"
    return response

and you can see more here

Answered By: sp 4_4
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.