Building a Dynamic Todo App with FastAPI and HTMX
December 22, 2024

Building a Dynamic Todo App with FastAPI and HTMX

Hello everyone! 👋 Amir from Bek Brace channel.
Today I want to share something exciting with you: building dynamic, server-rendered Todo applications using FastAPI and HTMX.
Trust me, this combination is a game changer for creating responsive web applications without drowning in JavaScript. Let’s get started!

Why choose FastAPI and HTMX?

FastAPI: a modern Python framework

FastAPI is like the Swiss Army Knife of Python web frameworks (I’m serious!). It’s fast (hence the name), easy to use, and has features like automatic API documentation and seamless asynchronous programming. Whether you’re a beginner or an experienced developer, FastAPI makes building APIs a breeze.

HTMX: JavaScript without writing JavaScript

HTMX is a lightweight JavaScript library that allows you to add interactivity to your applications using only HTML attributes. Forget writing complicated JavaScript — HTMX handles it for you. From making HTTP requests to dynamically exchanging page content, it’s the perfect tool for full-end developers who want to keep things simple.



what will we build

We will create a fully functional Todo application:

  • Dynamically list all your tasks.
  • Allows you to add, edit, and delete tasks without reloading the page.
  • Use HTMX to send requests and update the UI seamlessly.
  • Backend logic and templates rely on FastAPI.

By the end of this tutorial, you will have a solid understanding of how these tools work together.



Set up your project


1. Install dependencies

First, let’s get the required libraries:

pip install fastapi uvicorn jinja2
npm install htmx.org@2.0.4
Enter full screen mode

Exit full screen mode


2. Initialize your FastAPI application

Create a new Python file (main.py) and set up a basic FastAPI application:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
async def home():
    return ""
Enter full screen mode

Exit full screen mode

Run your application using the following command:

uvicorn main:app --reload
Enter full screen mode

Exit full screen mode

or

fastapi dev main.py
Enter full screen mode

Exit full screen mode

Open your browser and visit http://127.0.0.1:8000. Voila, your FastAPI application is live!



Use Jinja2 to add new templates

Server-rendered HTML is critical to our application. Let’s configure Jinja2:


Set template directory

Create a templates/ folder and add a index.html document:


 lang="en">

     charset="UTF-8">
     name="viewport" content="width=device-width, initial-scale=1.0">
    </span>Todo App<span class="nt"/>
<span class="nt"/>
<span class="nt"/>
    <span class="nt"/>Todo List<span class="nt"/>
    <span class="nt"/>
    <span class="nt"/>
<span class="nt"/>
<span class="nt"/>
</span></span></span></code></pre>
<div class="highlight__panel js-actions-panel">
<div class="highlight__panel-action js-fullscreen-code-action">
    <svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24" class="highlight-action crayons-icon highlight-action--fullscreen-on"><title>Enter full screen mode
    

Exit full screen mode

update your main.py Using Jinja2:

from fastapi.templating import Jinja2Templates
from fastapi.requests import Request

templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
Enter full screen mode

Exit full screen mode



Make it interact with HTMX

HTMX makes adding interactivity very easy. Let’s enhance our application.


Add new to-do item

in your index.htmlupdate the form to use HTMX:


Enter full screen mode

Exit full screen mode

exist main.py,Add to /todos Endpoint:

from fastapi import Form
from uuid import uuid4

class Todo:
    def __init__(self, text):
        self.id = uuid4()
        self.text = text
        self.done = False

@app.post("/todos", response_class=HTMLResponse)
async def add_todo(todo: str = Form(...)):
    new_todo = Todo(todo)
    todos.append(new_todo)
    return f"
  • {new_todo.text}"
  • Enter full screen mode

    Exit full screen mode


    list all

    Add a new route to present the to-do list:

    @app.get("/todos", response_class=HTMLResponse)
    async def list_todos():
        return "".join(f"
  • {todo.text}" for todo in todos)
  • Enter full screen mode

    Exit full screen mode

    update your index.html:

      id="todo-list" hx-get="/todos" hx-trigger="load">
    Enter full screen mode

    Exit full screen mode



    To sum up🙃

    That’s it! We built a fully interactive Todo application using FastAPI and HTMX. You’ve learned how to:

    1. Set up the FastAPI project.
    2. Use Jinja2 templates for server-rendered HTML.
    3. Use HTMX to achieve dynamic interactions without writing JavaScript.

    If you liked this tutorial, please share it with your friends/colleague developers/neighbors or anyone else 😆!
    🎄 I wish everyone a Merry Christmas and a Happy New Year 2025 🎄 Everyone

    2024-12-22 19:01:55

    Leave a Reply

    Your email address will not be published. Required fields are marked *