Home > Enterprise >  How to add custom headers to static files in fastapi
How to add custom headers to static files in fastapi

Time:02-01

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.

CodePudding user response:

Like this

from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get("/static/{file_path:path}")
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

  • Related