Skip to main content

FastAPI Static Files – Overview


FastAPI Static Files

Often, a web application needs to include resources that do not change, even when dynamic data is rendered. These resources are called static assets.

Examples of static files include:

  • Images (.png, .jpg)
  • JavaScript files (.js)
  • Stylesheets (.css)

Installing Required Library

To handle static files in FastAPI, you need the aiofiles library.

pip install aiofiles

Mounting Static Files

FastAPI uses the StaticFiles class to serve static content. You mount a folder (usually named static) so that all files inside it can be accessed via a URL.


from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

Example 1: Using an Image

Place an image file (for example, fa-logo.png) inside the static folder.

main.py


from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/hello/{name}", response_class=HTMLResponse)
async def hello(request: Request, name: str):
    return templates.TemplateResponse(
        "hello.html",
        {"request": request, "name": name}
    )

hello.html


<html>
  <body>
    <h2>Hello {{ name }} Welcome to FastAPI</h2>
    <img src="{{ url_for('static', path='fa-logo.png') }}" width="300">
  </body>
</html>

Example 2: Using JavaScript

JavaScript files can also be served as static assets. Create a file named hello.js inside the static folder.

hello.html


<html>
  <head>
    <title>My Website</title>
    <script src="{{ url_for('static', path='hello.js') }}"></script>
  </head>
  <body onload="myFunction()">
    <div id="time" style="text-align:right;"></div>
    <h1><div id="ttl">{{ name }}</div></h1>
  </body>
</html>

hello.js


function myFunction() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    var msg = "";

    if (h < 12) msg = "Good Morning, ";
    if (h >= 12 && h < 18) msg = "Good Afternoon, ";
    if (h >= 18) msg = "Good Evening, ";

    var x = document.getElementById("ttl").innerHTML;
    document.getElementById("ttl").innerHTML = msg + x;
    document.getElementById("time").innerHTML = h + ":" + m + ":" + s;
}
Summary: FastAPI serves static assets from a mounted directory. Templates use url_for('static', path='...') to safely reference images, JavaScript, and CSS files.

People are good at skipping over material they already know!

View Related Topics to







Contact Us

Name

Email *

Message *