Sling Academy
Home/FastAPI/FastAPI + Jinja: How to create custom filters

FastAPI + Jinja: How to create custom filters

Last updated: November 28, 2024

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.

Next Article: How to format date time in Jinja templates

Previous Article: How to pass variables from Python (FastAPI) to Jinja

Series: Jinja Templates

FastAPI

You May Also Like

  • Popular useful built-in Jinja filters you should know
  • How to remove consecutive whitespace in rendered Jinja pages
  • How to format large numbers with thousand separators in Jinja template
  • How to format date time in Jinja templates
  • How to pass variables from Python (FastAPI) to Jinja
  • How to decode Jinja response to string
  • How to create and use macros in Jinja
  • How to use namespace in Jinja
  • How to use if/ else in Jinja
  • How to use loops in Jinja
  • FastAPI + SQLAlchemy: Using cursor-based pagination
  • FastAPI: How to use macros in Jinja templates
  • Fixing Common Swagger UI Errors in FastAPI
  • FastAPI Error: 307 Temporary Redirect – Causes and Solutions
  • FastAPI Error: Expected UploadFile, received ‘str’
  • Resolving FastAPI ImportError: No Known Parent Package
  • FastAPI Error: No module named ‘pydantic_core._pydantic_core’
  • Resolving FastAPI 422 Error: Value is not a valid dict
  • Resolving the FastAPI Circular References Error