FastAPI, a modern web framework for building APIs with Python, combined with Jinja, a popular template engine for Python, makes a great duo for creating web applications that are both powerful and efficient. In this article, we’ll explore how to create custom filters with Jinja when using it with FastAPI.
Setting Up FastAPI and Jinja
Before we dive into custom filters, make sure you have FastAPI and Jinja installed. You can install these packages using pip:
pip install fastapi jinja2 uvicorn
Let's start by setting up a basic FastAPI application that uses Jinja for rendering templates.
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from jinja2 import Environment, FileSystemLoader
app = FastAPI()
# Set up Jinja Environment
template_loader = FileSystemLoader('templates')
template_env = Environment(loader=template_loader)
@app.get("/", response_class=HTMLResponse)
async def read_root():
template = template_env.get_template('index.html')
return template.render(name="World")
In this setup, we tell our FastAPI application to serve HTML from Jinja templates located in a "templates" folder.
Creating Custom Jinja Filters
To create a custom filter in Jinja, you'll define a Python function and then add it to your Jinja environment’s filter list. Let’s say we want to create a filter that capitalizes all words in a given string.
def capitalize_words(s):
return ' '.join(word.capitalize() for word in s.split())
template_env.filters['capitalize'] = capitalize_words
Now, you can use this custom filter in your Jinja templates like so:
{{ "hello world" | capitalize }}
This filter will process the provided text and return "Hello World".
Using Custom Filters in the Application
Let’s update our application to demonstrate the use of this custom filter. First, ensure you have a file named index.html
in the "templates" directory with the following content:
FastAPI + Jinja
{{ "fastapi and jinja with custom filters" | capitalize }}
Start your application using Uvicorn, FastAPI’s production-ready ASGI server:
uvicorn main:app --reload
You should see the capitalized title "Fastapi And Jinja With Custom Filters" when you visit http://127.0.0.1:8000 in your web browser.
Conclusion
Creating custom filters in Jinja allows you to extend its functionality and tailor it to meet your application’s needs. By integrating these with FastAPI, you can have clean and maintainable code for rendering your application’s HTML content. Have fun experimenting with more filters, and see how they can complement your FastAPI applications.