Using the FastAPI Python framework to return HTML templates with HTMX integration

Posted by


In this tutorial, we will be covering how to use the FastAPI Python framework to return HTML templates with HTMX integration. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+.

HTMX is a library that allows you to create dynamic web pages with minimal JavaScript. It simplifies the process of creating dynamic websites by allowing you to update sections of a page by making HTTP requests in the background.

Let’s start by setting up our project. First, you’ll need to create a new directory for your project and navigate into it:

mkdir fastapi-htmx-tutorial
cd fastapi-htmx-tutorial

Next, you’ll want to create a virtual environment for your project:

python3 -m venv venv

Activate the virtual environment:

source venv/bin/activate

Now, you can install FastAPI and HTMX using pip:

pip install fastapi uvicorn htmx[full]

Next, let’s create a FastAPI app. Create a new Python file called main.py in your project directory and add the following code:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
async def read_root():
    return """
    <html>
    <head>
        <title>FastAPI with HTMX</title>
        <script src="https://unpkg.com/htmx.org@1.6.0/dist/htmx.js"></script>
    </head>
    <body>
        <h1>Hello, FastAPI with HTMX!</h1>
        <button hx-get="/greet" hx-target="#greeting">Get Greeting</button>
        <div id="greeting"></div>
    </body>
    </html>
    """

@app.get("/greet", response_class=HTMLResponse)
async def get_greeting():
    return "<h2>Hello, HTMX!</h2>"

In this code, we define two endpoints. The first endpoint (root) returns an HTML template with a button that makes an HTMX request to the /greet endpoint when clicked. The /greet endpoint returns a simple greeting message.

Now, you can run the FastAPI app using the Uvicorn server:

uvicorn main:app --reload

After running the server, you can open your browser and navigate to http://localhost:8000 to see your FastAPI app in action.

When you click the "Get Greeting" button, you should see the message "Hello, HTMX!" appear under the button without the page refreshing.

That’s it! You’ve successfully set up a FastAPI app with HTMX integration for dynamic web page updates. FastAPI’s simplicity and performance combined with HTMX’s minimal JavaScript approach make for a powerful combination for building dynamic web applications.

0 0 votes
Article Rating

Leave a Reply

34 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@AlexGarcia-ir7fl
15 days ago

Do you know if there is something like Django-Compressor for FastAPI for sending static files like scripts? I am interested in combining this with pytailwindcss, it requires a build step but you get minimal css when using tailwind. Great tutorial btw!

@StrategicCIS
15 days ago

Nice video. Is there a second part with the DB setup? Thanks.

@_indrid_cold_
15 days ago

Phenomenal. I had been wondering about switching from Flask to FastAPI for some small web projects and this has convinced me to go for it. When I saw you were pulling in Tailwind I just knew you could be trusted. Excellent stuff this.

@mj2068
15 days ago

love your style, fast pace, dense and information rich, help me to focus and pay attention. keep up the great work.😊

@mericcapar2447
15 days ago

Hey thanks for the awesome content i was looking for FastAPI training.
I am having a issue and i couldn't solve it even i copy paste your codes. Whatever i do i can't get list of movies output. I only get

Movie List

{% include "table.html" %}
Film Name Director
Load More
this format. Can you help me or do you have any solution?

@niquedegraaff
15 days ago

Use Arel for browser refresh on reload. Otherwise you'll find yourself smashing the F5 button 6 mililons times per project….

@Darbokst
15 days ago

do you have a video showing the @app.get() section configured for a remote db?

@ZodakZach
15 days ago

plz do more fastAPI and htmx

@devilslide8463
15 days ago

“We don’t want a table embedded in a button as arguably not a best user experience “ Love that part 😂

@Felipe-bi3mk
15 days ago

Nice tutorial! I would have done 2 endpoints instead of looking at the headers, why that was your choice?

@grimonce
15 days ago

Superb

@chuckbenedict7235
15 days ago

Nice delivery. Well explained. Nice!

@wanomir3133
15 days ago

Great series! And I like the accent 😅

@alexanderscott2456
15 days ago

Is HTMX lighter than a kilogramme of steel or a kilogramme of feathers?

@seol-.-
15 days ago

Too GOOOD!

@junivensaavedra882
15 days ago

This is GOLD Man, my gratitude. 🙂

@SuperGrimmy
15 days ago

I bet these videos suddenly became more popular right now?

@samuelvishesh
15 days ago

What about SSE with jinja2 produced HTML partials in FastAPI?? 😮

@shinchikichin
15 days ago

You're awesome mate. Really liking your videos. Keep it up!

@falcomomo
15 days ago

Fantastic tutorial. Every step so clear and well described. I don't know why everyone doesn't do tutorials like this.

34
0
Would love your thoughts, please comment.x
()
x