You have a FastAPI app running, the API docs look great, but the browser tab still shows a blank square or the default globe icon. This is a common issue: FastAPI does not automatically serve a favicon, and unlike Flask or Django, it has no built-in convention for one. The fix is straightforward once you know where to put the file and how to expose it.
In this guide, we will walk through the exact steps to serve a fastapi favicon using StaticFiles, a dedicated route, or a template tag. We will also cover the HTML markup that makes browsers pick up the icon reliably, plus the pitfalls that cause 404s and stale icons.
Prerequisites
Before you start, make sure you have:
A working FastAPI project (any version that supports StaticFiles, which is all modern versions).
A favicon file ready. You can use an ICO, PNG, or SVG. If you need to create one, see our HTML favicon guide or generate a multi-size ICO with Mzu favicondl.
Basic familiarity with FastAPI routing and Jinja2 templates (if you serve HTML).
Step 1: Place the favicon file in a static directory
Create a folder named static at the root of your project (or anywhere you prefer). Put your favicon file inside it. For maximum compatibility, name it favicon.ico and also include a PNG or SVG version if you have one.
If you only have a PNG, that works too—just reference it correctly in the HTML. The ICO format is still requested by browsers when no link tag is present, so having /favicon.ico available avoids a 404 in the console.
Step 2: Mount StaticFiles in your FastAPI app
FastAPI uses Starlette's StaticFiles to serve static assets. Add this to your main.py:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')
This makes any file in static/ available at /static/filename. So your favicon will be at /static/favicon.ico.
Step 3: Add the link tag in your HTML
If you serve HTML templates (using Jinja2Templates), add the favicon link inside the <head> of your base template. The rel attribute must be icon according to the HTML specification.
If you also have an SVG or PNG, include them with appropriate type attributes. Browsers will pick the best supported format. For a deeper dive into link tag order, see our favicon link tag guide.
Step 4: Serve /favicon.ico directly (optional but recommended)
Browsers and some tools still request /favicon.ico at the root even if you have a link tag. To avoid a 404, you can add a dedicated route that returns the file:
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get('/favicon.ico', include_in_schema=False)
async def favicon():
return FileResponse('static/favicon.ico')
The include_in_schema=False keeps it out of the auto-generated docs. This route is especially useful for API-only apps that do not serve HTML but still want a clean network tab.
Step 5: Verify the setup
Start your server and open the app in a browser. Check the network tab: the favicon request should return 200. If you see a 404, confirm the file path and that the mount point matches the URL in your link tag. You can also use a favicon checker tool to audit the icon across browsers.
Common pitfalls
Wrong mount path: If you mount StaticFiles at /static, the URL must be /static/favicon.ico, not /favicon.ico.
Missing file: FastAPI will return a 404 if the file does not exist in the directory. Double-check the filename and extension.
Cache issues: Browsers cache favicons aggressively. After updating, do a hard refresh or clear the favicon cache. See our cache clearing guide.
SVG without proper MIME type: If you serve an SVG favicon, ensure the server sends image/svg+xml. StaticFiles usually handles this, but some custom routes may not.
Template path errors: If using Jinja2, make sure the href is an absolute path starting with / or use url_for to generate it.
Conclusion
Serving a favicon in FastAPI is a matter of placing the file, mounting a static directory, and adding the correct link tag. For API-only apps, a simple route for /favicon.ico keeps logs clean. Once set up, your app will show a proper icon in browser tabs, bookmarks, and history—no more blank squares.
FastAPI 앱은 이미 실행 중이고 API 문서도 보기 좋지만, 브라우저 탭에는 여전히 빈 사각형이나 기본 지구본 아이콘이 표시됩니다. 이는 흔한 문제입니다. FastAPI는 favicon을 자동으로 제공하지 않으며, Flask나 Django와 달리 이를 위한 built-in 규약도 없습니다. 파일을 어디에 두고 어떻게 노출할지만 알면 해결할 수 있습니다.
이 가이드에서는 StaticFiles, 전용 route 또는 template tag를 사용해 fastapi favicon을 제공하는 정확한 과정을 살펴봅니다. 브라우저가 아이콘을 안정적으로 인식하도록 하는 HTML markup과 함께, 404 오류와 stale icon 문제를 일으키는 흔한 실수도 다룹니다.
사전 준비 사항
시작하기 전에 다음 사항을 확인하세요.
작업이 가능한 FastAPI 프로젝트(StaticFiles를 지원하는 버전이면 되며, 모든 최신 버전이 해당합니다).
SVG나 PNG도 함께 사용한다면 각각 적절한 type attribute를 지정해 포함하세요. browser는 지원하는 format 중 가장 적합한 것을 선택합니다. link tag 순서를 더 자세히 알아보려면 favicon link tag guide를 참고하세요.
4단계: /favicon.ico 직접 제공(선택 사항이지만 권장)
link tag를 추가했더라도 browser와 일부 도구는 여전히 root에서 /favicon.ico를 요청합니다. 404를 피하려면 file을 반환하는 전용 route를 추가할 수 있습니다.
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get('/favicon.ico', include_in_schema=False)
async def favicon():
return FileResponse('static/favicon.ico')
include_in_schema=False를 지정하면 auto-generated docs에서 해당 route가 제외됩니다. 이 route는 HTML을 제공하지 않으면서도 network tab을 깔끔하게 유지하고 싶은 API-only app에 특히 유용합니다.
5단계: 설정 확인
server를 시작하고 browser에서 app을 열어 보세요. network tab을 확인하세요. favicon request가 200을 반환해야 합니다. 404가 보이면 file path를 확인하고, mount point가 link tag에 지정한 URL과 일치하는지 확인하세요. browser 전반에서 icon을 점검하려면 favicon checker tool을 사용할 수도 있습니다.
흔한 함정
잘못된 mount path: StaticFiles를 /static에 mount하는 경우 URL은 /favicon.ico가 아니라 /static/favicon.ico여야 합니다.
파일 누락: 파일이 디렉터리에 존재하지 않으면 FastAPI는 404를 반환합니다. 파일명과 확장자를 다시 확인하십시오.
캐시 문제: 브라우저는 favicon을 적극적으로 캐시합니다. favicon을 업데이트한 뒤에는 hard refresh를 하거나 favicon 캐시를 지우십시오. 자세한 내용은 캐시 삭제 가이드를 참고하십시오.
올바른 MIME type이 없는 SVG: SVG favicon을 제공할 때 서버가 image/svg+xml을 전송하는지 확인해야 합니다. StaticFiles는 일반적으로 이를 처리하지만, 일부 custom route에서는 처리하지 않을 수 있습니다.
Template 경로 오류: Jinja2를 사용하는 경우 href이 /로 시작하는 absolute path인지 확인하거나, url_for를 사용해 생성하십시오.
결론
FastAPI에서 favicon을 제공하는 것은 파일을 배치하고 static 디렉터리를 mount한 다음 올바른 link tag를 추가하는 것으로 해결할 수 있습니다. API 전용 앱이라면 /favicon.ico를 위한 간단한 route를 추가해 로그를 깔끔하게 유지할 수 있습니다. 설정이 끝나면 브라우저 탭, 북마크, 기록에 앱의 아이콘이 정상적으로 표시되어 더 이상 빈 사각형이 나타나지 않습니다.
Tienes una aplicación FastAPI en funcionamiento y la documentación de la API se ve muy bien, pero la pestaña del navegador sigue mostrando un cuadrado vacío o el icono predeterminado del globo. Es un problema habitual: FastAPI no sirve automáticamente un favicon y, a diferencia de Flask o Django, no incluye una convención integrada para él. La solución es sencilla cuando sabes dónde colocar el archivo y cómo exponerlo.
En esta guía te mostraremos los pasos exactos para servir un fastapi favicon usando StaticFiles, una ruta dedicada o una etiqueta de plantilla. También explicaremos el marcado HTML que hace que los navegadores detecten el icono de forma fiable, además de los errores que provocan 404 e iconos obsoletos.
Requisitos previos
Antes de empezar, asegúrate de tener:
Un proyecto FastAPI que funcione (cualquier versión compatible con StaticFiles, es decir, todas las versiones modernas).
Un archivo favicon listo. Puedes usar un ICO, PNG o SVG. Si necesitas crear uno, consulta nuestra guía de favicon en HTML o genera un ICO de varios tamaños con Mzu favicondl.
Familiaridad básica con el enrutamiento de FastAPI y las plantillas Jinja2 (si sirves HTML).
Paso 1: Coloca el archivo favicon en un directorio estático
Crea una carpeta llamada static en la raíz de tu proyecto (o donde prefieras). Coloca dentro el archivo favicon. Para máxima compatibilidad, ponle el nombre favicon.ico y, si tienes una versión PNG o SVG, inclúyela también.
Si solo tienes un PNG, también funciona; basta con referenciarlo correctamente en el HTML. El formato ICO sigue siendo solicitado por los navegadores cuando no está presente una etiqueta link, por lo que tener /favicon.ico disponible evita un 404 en la consola.
Paso 2: Monta StaticFiles en tu aplicación FastAPI
FastAPI utiliza StaticFiles de Starlette para servir archivos estáticos. Añade lo siguiente a tu main.py:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')
Esto hace que cualquier archivo de static/ esté disponible en /static/filename. Por tanto, tu favicon estará en /static/favicon.ico.
Paso 3: Añade la etiqueta link en tu HTML
Si sirves plantillas HTML (usando Jinja2Templates), incluye el enlace al favicon dentro del <head> de tu plantilla base. El atributo rel debe tener el valor icon, según la especificación HTML.
Si también tienes un SVG o PNG, inclúyelos con los atributos type correspondientes. Los navegadores seleccionarán el formato mejor compatible. Para profundizar en el orden de los link tags, consulta nuestra guía sobre el link tag del favicon.
Paso 4: Sirve /favicon.ico directamente (opcional, pero recomendado)
Los navegadores y algunas herramientas siguen solicitando /favicon.ico en la raíz aunque tengas un link tag. Para evitar un 404, puedes añadir una ruta específica que devuelva el archivo:
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get('/favicon.ico', include_in_schema=False)
async def favicon():
return FileResponse('static/favicon.ico')
El parámetro include_in_schema=False mantiene la ruta fuera de la documentación generada automáticamente. Esta ruta es especialmente útil para aplicaciones solo de API que no sirven HTML, pero que sí quieren una pestaña de red limpia.
Paso 5: Verifica la configuración
Arranca tu servidor y abre la aplicación en un navegador. Comprueba la pestaña de red: la solicitud del favicon debería devolver un 200. Si ves un 404, verifica la ruta del archivo y que el punto de montaje coincida con la URL de tu link tag. También puedes usar una herramienta de comprobación de favicons para revisar el icono en distintos navegadores.
Errores comunes
Ruta de montaje incorrecta: Si montas StaticFiles en /static, la URL debe ser /static/favicon.ico, no /favicon.ico.
Archivo inexistente: FastAPI devolverá un 404 si el archivo no existe en el directorio. Comprueba que el nombre y la extensión sean correctos.
Problemas de caché: Los navegadores almacenan los favicon en caché de forma agresiva. Después de actualizarlo, haz una recarga forzada o borra la caché del favicon. Consulta nuestra guía para limpiar la caché.
SVG sin el MIME type correcto: Si sirves un favicon SVG, asegúrate de que el servidor envíe image/svg+xml. StaticFiles normalmente se encarga de esto, pero algunas rutas personalizadas puede que no lo hagan.
Errores en la ruta de la plantilla: Si usas Jinja2, asegúrate de que el href sea una ruta absoluta que empiece por / o utiliza url_for para generarla.
Conclusión
Servir un favicon en FastAPI consiste en colocar el archivo, montar un directorio estático y añadir la etiqueta link correcta. En las aplicaciones que solo ofrecen una API, una ruta sencilla para /favicon.ico mantiene limpios los logs. Una vez configurado, tu aplicación mostrará un icono adecuado en las pestañas, los marcadores y el historial del navegador: se acabaron los cuadrados en blanco.
Need a favicon for your FastAPI app?
Generate ICO, PNG, and SVG icons in seconds with Mzu favicondl. Free, fast, and no sign-up required.