Categories
Tags
30days AI ai backend blog blogging booking burnout career chatbot cms coding design development devops django docker email express fastapi flight Flight Booking System full stack full-stack gmail GPT-3 interviews journey LinkedIn MERN mongodb NextJS nextjs notion OpenAI openai planning portfolio programming project python react ReactJS search sendgrid smtp software software development tailwind
236 words
1 minutes
Day 20 of 30 Days of FastAPI - Static Files & Templates — Creating a UI for your API
Welcome back! After a short Sunday’s break, we are adding a visual layer to our API. Sometimes, you need a simple dashboard or a landing page to show off your work.
1. Folder Structure
To keep things clean, we adopt a standard directory structure.
.
├── static/ # CSS, JS, Images
├── templates/ # HTML files (Jinja2)
├── main.py
└── ...
2. Serving Static Files
FastAPI uses StaticFiles from Starlette to “mount” a directory. This makes files like style.css accessible at /static/style.css.
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

3. Rendering HTML with Jinja2
Instead of returning a dict, we now return a TemplateResponse. This allows us to pass variables from our Python code into our HTML.
from fastapi.templating import Jinja2Templates
from fastapi import Request
templates = Jinja2Templates(directory="templates")
@app.get("/welcome/{user_name}")
async def welcome_user(request: Request, user_name: str):
return templates.TemplateResponse(
"index.html",
{"request": request, "name": user_name}
)
4. Why the request object?
You might notice we pass the request in the context. Jinja2 requires this to generate URLs and handle internal logic correctly.
🛠️ Implementation Checklist
- Installed
jinja2using uv add jinja2. - Created
static/andtemplates/folders. - Mounted the static directory in
main.py. - Created a base HTML template and rendered it via a GET route.
- Verified that my custom Starlette error handler still works (it will still return JSON, which is perfect for API debugging even if the UI fails!).
📚 Resources
- Official Docs: FastAPI Static Files
- Official Docs: FastAPI Templates
- Book: FastAPI: Modern Python Web Development (Chapter 9: Templates and Static Files).
Day 20 of 30 Days of FastAPI - Static Files & Templates — Creating a UI for your API
https://beyond400.vercel.app/posts/fastapi-20/

