Serving Static Files in FastAPI

Git commit: serve static files with aiofiles
Ok, the navbar was good, but something is missing, our brand logo, no? In this post, we will be adding an image/logo to our navbar. Before that let's understand static and media files in a hurry. When we fill out a form, say a form that asks for an image upload from a computer. Then the image uploaded by us is called a media.
But when a webpage shows us an image or provides CSS, js file to the browser, it's a static file. Ok, now let's add our logo to the navbar. For serving static files, we will make use of a library named aiofiles. Let's add this to our requirements.txt file.

Jinja2==3.1.2
aiofiles==23.1.0

Now, install aiofiles with pip install -r requirements.txt. Now, since this static file configuration is not specific to a particular route, I am going to modify our main.py file to support static files.

from fastapi.staticfiles import StaticFiles

def include_router(app):
    app.include_router(api_router)
    app.include_router(app_router)

#new
def configure_staticfiles(app):
    app.mount("/static", StaticFiles(directory="static"), name="static")

def start_application():
    app = FastAPI(title=settings.PROJECT_NAME, version=settings.PROJECT_VERSION)
    create_tables()
    include_router(app)
    configure_staticfiles(app)  #new
    return app
  • Basically, we are informing fastapi that we are going to keep all our static files in a folder named 'static' and whenever it has to search for a static file, say an image, don't search here and there. It will be inside 'static' folder only.

Ok, this part is complete, now let's put an image in the path static > images > logo.png.

📁 backend/
├─📄 .env
├─📄 .env.example
├─📁 alembic/
├─📄 alembic.ini
├─📁 static/        #new directory
│ ├─📁 images/
│   ├─📄 shots.png  
├─📁 core/
├─📁 db/
├─📄 main.py
└─📄 requirements.txt

To include a static file in the template we make use of url_for template tag. e.g. 

<img src="{{ url_for('static', path='images/jb.png') }}" alt="" width="30" height="24">

<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
Ok, now let's modify our navbar.html file to have a brand image.

<nav class="navbar navbar-expand-lg bg-body-tertiary">
    <div class="container-fluid">
      <img src="{{ url_for('static', path='images/shots.png') }}" alt="" width="30" height="24" class="mx-4">
      <a class="navbar-brand" href="#">Algoholic</a>
       <!--old code here-->
  </nav>

Now, you should have a logo in the navbar.

FastAPITutorial

Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.

We know, we might make it hard for you but definitely worth the efforts.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial