How do I set a favicon for all pages in my FastAPI project?
How do I set a favicon for all pages in my FastAPI project?
Just return a FileResponse in the GET request to /favicon.ico
File structure:
root
|-main.py
|-favicon.ico
main.py
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
favicon_path = 'favicon.ico'
@app.get('/favicon.ico')
async def favicon():
return FileResponse(favicon_path)
To hide the path operation from the schema (used to make the docs), add include_in_schema=False to the decorator (credit@Tom Pohl):
@app.get('/favicon.ico', include_in_schema=False)
I had this same issue and dorked around trying different things and it only started working after I mounted folder for static files.
In main.py
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
In home.html head area
<link id="favicon" rel="icon" type="image/x-icon" href="static/images/favicon.ico">
I suspect it's related to folder permissions.