FastAPI is a modern web framework for building APIs with Python, while Jinja2 is a popular templating engine used for generating dynamic HTML content. In this tutorial, we will explore how to integrate FastAPI with Jinja2 to create a web application.
Step 1: Install Dependencies
First, we need to install the necessary dependencies. You can do this by using pip:
pip install fastapi uvicorn jinja2
Step 2: Create a FastAPI App
Next, let’s create a FastAPI app. Create a new Python file, e.g., app.py, and add the following code:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from jinja2 import Environment, FileSystemLoader
app = FastAPI()
# Create a Jinja2 environment
env = Environment(loader=FileSystemLoader('templates'))
@app.get('/', response_class=HTMLResponse)
async def read_root():
template = env.get_template('index.html')
content = template.render(title='FastAPI with Jinja2')
return content
Step 3: Create Templates
Create a new directory called templates, and add an HTML file called index.html. You can add some basic HTML content to this file, e.g.,
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome to FastAPI with Jinja2</h1>
</body>
</html>
Step 4: Run the FastAPI App
You can start the FastAPI app by running the following command in the terminal:
uvicorn app:app --reload
You should see a message indicating that the FastAPI app is running. Visit http://127.0.0.1:8000/ in your browser to see the output of the Jinja2 template.
Step 5: Passing Data to Templates
You can pass data from your FastAPI app to the Jinja2 templates by including variables in the render method. For example, you can update the read_root function to pass a list of items to the template:
@app.get('/', response_class=HTMLResponse)
async def read_root():
items = ['item1', 'item2', 'item3']
template = env.get_template('index.html')
content = template.render(title='FastAPI with Jinja2', items=items)
return content
You can then update the index.html template to display the list of items:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome to FastAPI with Jinja2</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
Step 6: Handling Form Submissions
You can also use FastAPI to handle form submissions and pass the form data to Jinja2 templates. Update your FastAPI app to handle POST requests and display the form data in the template:
from fastapi import FastAPI, Form
from fastapi.responses import HTMLResponse
@app.post('/submit', response_class=HTMLResponse)
async def submit_form(item: str = Form(...)):
template = env.get_template('index.html')
content = template.render(title='Form Submission', item=item)
return content
Add a form to the index.html template to allow users to submit data:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome to FastAPI with Jinja2</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<form action="/submit" method="post">
<input type="text" name="item">
<input type="submit" value="Submit">
</form>
</body>
</html>
That’s it! You have successfully integrated FastAPI with Jinja2 to create a web application. FastAPI’s async support and Jinja2’s templating capabilities make for a powerful combination for building dynamic web applications. Feel free to explore more features of FastAPI and Jinja2 to further enhance your web development projects.
awesome tutorial.. love the way you explained every detail
That was awesome!
Please guide how to integrate fastapi with Gemini integration
Please guide us how to integrate any project in fastapi
Absolutelly great content. Thank you!
5:04 man what the hell is that "for dog in dogs" 😂😆😜😂
Great very clear
This tutorial is great – music just a little too loud
your face position in video is annoying, please move to the right side
Your content is pretty well explained!
Would you be considering making a course in the future for ML engineers/ Data Scientists to deploy web apps using fast API with an easier frontend framework? As a DS it's a bit overwhelming to learn Javascript/ html/ css or its dependencies as it moves me away from my core expertise and also do not want to miss out capabilities of fast API.😅
The explanation was very good, Thank you.
Yeah… the web browser just shows "null" in chrome.
When I revert to the Non-Jinja2 way, it works.
A very useful example, efficiently explained. Thank you!
The best teacher I 've ever met.
Hello,
What are we storing in the request class that we have in our function?
I'm doing a simple command where if I click a <button> it does some function.
How do I do that? I'm guessing it has something to do with onclick event in javascript?
Have you got any training on using FastAPI and SQLModel to connect to a remote database?
I've got a MySQL DB on a digital ocean droplet that I want to access.
Thanks.
This was well explained. Thanks.