FastAPI Quickstart Part 06: Implementing HTML with Jinja2, Serving StaticFiles css, and Handling Redirects | #python #fastapi #letscode

Posted by

FastAPI Quickstart part:06 HTML w/ Jinja2, StaticFiles css, Redirect

FastAPI Quickstart part:06 HTML w/ Jinja2, StaticFiles css, Redirect

In this tutorial, we will learn how to integrate HTML templates with Jinja2, serve static CSS files with StaticFiles, and redirect users to different pages using FastAPI.

HTML with Jinja2

First, let’s install the Jinja2 library using pip:


pip install Jinja2

Next, we will create an HTML template using Jinja2:

{{ title }}

Hello, {{ name }}!

We can render this template in our FastAPI application using the following code:


from fastapi import FastAPI
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/")
def index(name: str):
return templates.TemplateResponse("index.html", {"request": request, "name": name})

Serving Static CSS Files

To serve static CSS files, we can use the StaticFiles class provided by FastAPI:


from fastapi.staticfiles import StaticFiles

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

@app.get("/")
def index():
return {"message": "Hello, World!"}

Now, we can place our CSS files in a directory called “static” and access them through the “/static” route.

Redirecting Users

To redirect users to a different page, we can use the RedirectResponse class provided by FastAPI:


from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()

@app.get("/")
def index():
return RedirectResponse(url="/home")

When users access the root route “/”, they will be redirected to the “/home” route.

We have now successfully integrated HTML templates with Jinja2, served static CSS files, and redirected users to different pages using FastAPI.