HTMX is a powerful tool that lets you build interactive frontends without writing much (or any) custom JavaScript. It’s ideal for developers who prefer server-driven logic but still want snappy, dynamic interfaces. In this guide, we’ll use HTMX to consume a REST API and dynamically update our UI — all with minimal JS.
Step 1: Set Up the Backend API
We'll use Flask to create a simple REST API. If you don't already have Flask installed:
pip install flask flask-cors
Create api.py
:
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/api/messages")
def get_messages():
return jsonify([
{ "id": 1, "text": "Hello from the API!" },
{ "id": 2, "text": "HTMX is awesome." },
{ "id": 3, "text": "This feels like magic." }
])
if __name__ == "__main__":
app.run(port=5001)
Run this API on port 5001
and keep it running.
Step 2: Set Up the Frontend App
Now let's build a simple frontend in Flask that uses HTMX to hit that REST endpoint and render it server-side using Jinja2.
Create app.py
:
from flask import Flask, render_template, request
import requests
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/messages")
def messages():
response = requests.get("http://localhost:5001/api/messages")
messages = response.json()
return render_template("partials/messages.html", messages=messages)
if __name__ == "__main__":
app.run(debug=True)
Step 3: Create the HTML Templates
Inside templates/index.html
:
HTMX + REST API
HTMX with REST APIs
Messages will appear here...
Create templates/partials/messages.html
:
{% for msg in messages %}
{{ msg.text }}
{% endfor %}
Step 4: Run Both Servers
Start both the API (api.py
) and the frontend (app.py
). Then open your browser to http://localhost:5000/
.
Click the "Load Messages" button - it will fetch the JSON from your REST API, render it server-side with Jinja2, and inject the HTML into the page.
✅ Pros:
- 🔄 Use REST APIs without JavaScript frameworks
- 🧠 Leverages existing Python skills and Jinja2 templates
- 🚀 Keeps the frontend lightweight and fast
⚠️ Cons:
- 🌐 Slightly more server-side processing per request
- 🔌 Extra integration layer (your frontend must act as the middleman for the API)
Summary
HTMX bridges the gap between static HTML and dynamic apps. In this tutorial, we used it to fetch data from a REST API and inject rendered HTML into the page - all with minimal JS and a clean Flask backend.
📘 Want to go further?
If you're ready to build full HTMX-powered apps without ever touching a heavy frontend framework, check out my 24-page PDF tutorial for just $10:
👉 HTMX Tutorial: Build Modern Web Apps Without JavaScript Frameworks
If this helped you out, also consider buying me a coffee: Buy Me a Coffee ☕