Sling Academy
Home/FastAPI/How to pass variables from Python (FastAPI) to Jinja

How to pass variables from Python (FastAPI) to Jinja

Last updated: November 28, 2024

FastAPI is a modern, fast web framework for building APIs with Python. One common requirement when creating web applications is to render dynamic content, which is achieved using templates. Jinja is a popular templating engine for Python that allows developers to pass variables from their backend code (such as a FastAPI application) to the front end (an HTML template).

Setting Up FastAPI with Jinja Templating

First, let’s set up a basic FastAPI application with Jinja2. Ensure you have FastAPI and Jinja2 installed in your environment:

pip install fastapi uvicorn jinja2

Now, create a FastAPI application with a single route that uses a Jinja template.

from fastapi import FastAPI
from starlette.responses import HTMLResponse
from jinja2 import Template

Let's define our FastAPI app and a basic route:

app = FastAPI()

template = Template("Hello {{ name }}!")

@app.get("/hello/{name}", response_class=HTMLResponse)
async def read_item(name: str):
    rendered_template = template.render(name=name)
    return rendered_template

Here, we've used a simple Jinja template embedded in our code. When accessing the route /hello/{name}, it will render HTML output by replacing {{ name }} with the provided variable.

Passing Multiple Variables

In practice, you may need to pass more than one variable to your templates. Let’s demonstrate how to do that:

from fastapi import FastAPI
from starlette.responses import HTMLResponse
from jinja2 import Template

app = FastAPI()

template = Template("<html><body><h1>Welcome, {{ user.name }}!</h1><p>You have {{ user.messages }} messages.</p></body></html>")

@app.get("/user/{username}/{num_messages}", response_class=HTMLResponse)
async def read_user(username: str, num_messages: int):
    user_info = {
        "name": username,
        "messages": num_messages
    }
    rendered_template = template.render(user=user_info)
    return rendered_template

In this example, you can see how we pass a dictionary as a variable to the Jinja template, allowing access to subkeys within the template.

Using Templating Files

For real-world applications, it is best practice to separate templates from your Python code. First, organize your project's folder structure. For demonstration purposes, create a folder templates/ to store your HTML files.

An example folder structure:

/project
  |-- main.py
  |-- templates
      |-- hello.html

Update main.py:

from fastapi import FastAPI
from starlette.responses import HTMLResponse
from jinja2 import Environment, FileSystemLoader

app = FastAPI()

env = Environment(loader=FileSystemLoader("templates"))
template = env.get_template("hello.html")

@app.get("/hello/{name}", response_class=HTMLResponse)
async def read_item(name: str):
    rendered_template = template.render(name=name)
    return rendered_template

Create a file named hello.html in the templates directory with the following content:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Greeting</title>

Now when you access http://localhost:8000/hello/YourName, the application will make use of the hello.html template file to render the Hello YourName! message.

Conclusion

Using Jinja2 with FastAPI enables you to create dynamic, template-driven web pages by passing variables from Python code to HTML templates. Separating template management into files helps maintain clean and manageable projects as your application grows.

Run your FastAPI app with:

uvicorn main:app --reload

This completes your setup and example of how to pass variables from Python (FastAPI) to Jinja templates.

Next Article: FastAPI + Jinja: How to create custom filters

Previous Article: How to decode Jinja response to string

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
  • FastAPI + Jinja: How to create custom filters
  • 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