← Back to list

The Need for Templating in FastAPI

One may ask, “Why use templating and Jinja2 templating stuff when I can just use the HTMLResponse class?”

Aarif Mahdi · 2026-05-24 19:42 · 0 claps · 1.4 min read
#fastapi #jinja2
Open on Medium ↗
Wiki topics: 🌐 · Web Development

credits (for img): https://realpython.com/fastapi-jinja2-template/

credits (for img): https://realpython.com/fastapi-jinja2-template/

The Need for Templating in FastAPI

One may ask, “Why use templating and Jinja2 templating stuff when I can just use the HTMLResponse class?”

Well, the straightforward answer is, “While returning HTML strings directly from your endpoints is straightforward, it has limitations. Reusing HTML components, managing complex layouts, and keeping Python logic separate from HTML markup all become difficult. These challenges are exactly what templates are designed to address.”

I’ll now explain the above pain points.

  1. Reusing HTML Components: Say you used HTML strings directly in your code. Now you want to reuse that HTML. Can you do that? Of course, copy-paste it, right? But that’s code duplication, which does not build maintainable applications. (more on this issue later) What to do then? Use templating; the Jinja2Templates class in FastAPI gives you a feature called “template inheritance”, which allows you to reuse HTML components in your code. First issue solved, nice.
  2. Managing Complex Layouts: This ties directly to our first problem, which means that we cannot manage the HTML files’ content when our application grows and we create more and more HTML files. Templating solves this by letting you define one “base” layout, also called a Parent template, that all other pages safely inherit (they’re called Child templates).
  3. Keeping Python Logic Separate from HTML Markup: When you write HTML strings inside your Python file (e.g, main.py), it works, and the application works. But it’s not considered a good practice. Separate your Python and HTML into separate files. This is better for the readability and maintainability of your application(s).

Bonus Information:

  • Template inheritance is a feature of Jinja2 itself. FastAPI’s Jinja2Templates class simply integrates it into your API routes.
  • Security POV: Raw HTML strings are highly vulnerable to Cross-Site Scripting (XSS) attacks if you inject user input manually. Jinja2 automatically escapes HTML characters, making your app secure by default.

메타데이터
post_id
ffd9cda2687b
slug
the-need-for-templating-in-fastapi-ffd9cda2687b
url
https://medium.com/@mahdiaarif6/the-need-for-templating-in-fastapi-ffd9cda2687b
canonical_url
https://medium.com/@mahdiaarif6/the-need-for-templating-in-fastapi-ffd9cda2687b
author_url
https://medium.com/@mahdiaarif6
status
ok
fetched_at
2026-07-10 14:10:06