FastAPI - Static Files

Often it is required to include in the template response some resources that remain unchanged even if there is a certain dynamic data. Such resources are called static assets. Media files (.png, .jpg etc), JavaScript files to be used for executing some front end code, or stylesheets for formatting HTML (.CSS files) are the examples of static files.

In order to handle static files, you need a library called aiofiles

pip3 install aiofiles

Next, import StaticFiles class from the fastapi.staticfiles module. Its object is one of the parameters for the mount() method of the FastAPI application object to assign "static" subfolder in the current application folder to store and serve all the static assets of the application.

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


In the following example, FastAPI logo is to be rendered in the hello.html template. Hence, “fa-logo.png” file is first placed in static folder. It is now available for using as src attribute of <img> tag in HTML code.

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})

The HTML code of \templates\hello.html is as follows −

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

Run the Uvicorn server and visit the URL as http://localhost/hello/Vijay. The Logo appears in the browser window as shown.

FastAPI Static Files


Here is another example of a static file. A JavaScript code hello.js contains a definition of myfunction() to be executed on the onload event in following HTML script (\templates\hello.html)

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

The hello.js code is as follows − (\static\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;

The function detects the value of current time and assigns appropriate value to msg variable (good morning, good afternoon or good evening) depending on the time of the day.

Save /static/hello.js, modify \templates\hello.html and restart the server. The browser should show the current time and corresponding message below it.

FastAPI Static Files FastAPI Static Files
Kickstart Your Career

Get certified by completing the course

Get Started