DEV Community

Anurag Singh
Anurag Singh

Posted on • Edited on

1

Supercharge Your FastAPI Development with Browser Hot Reloading Using Arel

Ever found yourself muttering, “Why can’t my FastAPI app just refresh the browser automatically when I make a change?” Trust me, you’re not alone. As a web developer working with Python ASGI frameworks like FastAPI for a full stack application, those constant manual reloads can be a real buzzkill. Enter Arel – your new best friend for adding seamless hot-reloading to your FastAPI projects. Let’s dive into how you can integrate Arel into your workflow and transform your development experience!

FastAPI and the Quest for Hot Reloading

FastAPI is a fantastic, high-performance framework for building APIs with Python. It’s built on top of ASGI (Asynchronous Server Gateway Interface) and leverages the Uvicorn web server to deliver a sleek and efficient development experience. However, out of the box, FastAPI doesn’t come with built-in browser hot-reloading. That’s where Arel steps in.

Introducing Arel

Arel is a lightweight library designed to implement development-only hot-reloading for non-Python files that are not dynamically read from disk on each request. This includes:

  • HTML templates
  • GraphQL schemas
  • Cached rendered Markdown content
  • Static assets

Key Features

  • Real-time file change detection
  • WebSocket-based browser notifications
  • Customizable reload hooks
  • Minimal performance overhead

How Does Arel Work?

Arel keeps an eye on the files you specify. When it detects a change, it sends a notification to the browser via WebSocket. An injected client script then triggers a page reload, ensuring your latest changes are visible immediately. You can also register custom reload hooks for any additional server-side operations, such as refreshing cached content or re-initializing other resources.

Installing Arel

First things first, let’s get Arel installed. Open your terminal and run:

pip install arel

Package Requirements

To ensure everything runs smoothly, make sure you have the following packages installed:

  • arel
  • fastapi
  • jinja2
  • uvicorn[standard] or websockets

You can install them all at once like this:

pip install arel fastapi jinja2 uvicorn[standard]

Setting Up Arel with FastAPI

Let’s walk through setting up Arel in your FastAPI project. I’ve also shared a GitHub repository with a complete example you can reference.

Project Structure

Here’s a quick glance at the structure of the project:

├── main.py
├── templates
│   ├── base.html
│   └── index.html
└── requirements.txt
Enter fullscreen mode Exit fullscreen mode

Templates Configuration

base.html: Your base template sets up the structure for your HTML pages and includes the hot-reload script when in debug mode.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FastAPI with Arel</title>
</head>
<body>
    {% block content %}{% endblock %}

    <!-- Hot reload script -->
    {% if DEBUG %}
        {{ hot_reload.script(url_for('hot-reload')) | safe }}
    {% endif %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

index.html: This is a simple template that extends base.html and contains some content to demonstrate hot reloading.

{% extends "base.html" %}

{% block content %}
    <h1>Testing Hot Reloading</h1>
    <p>Look! Auto hot-reloading in action. It sure makes development a breeze!</p>
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

Main Application Setup

Here’s how you can set up your main.py to integrate Arel with FastAPI:

import os
import arel
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates("templates")

if _debug := os.getenv("DEBUG"):
    hot_reload = arel.HotReload(paths=[arel.Path(".")])
    app.add_websocket_route("/hot-reload", route=hot_reload, name="hot-reload")
    app.add_event_handler("startup", hot_reload.startup)
    app.add_event_handler("shutdown", hot_reload.shutdown)
    templates.env.globals["DEBUG"] = _debug
    templates.env.globals["hot_reload"] = hot_reload

@app.get("/")
def index(request: Request):
    return templates.TemplateResponse("index.html", context={"request": request})
Enter fullscreen mode Exit fullscreen mode

Enabling Hot Reloading

To activate hot reloading, you need to set the DEBUG flag to True. You can do this directly in your FastAPI application or by using an environment variable.

Setting Debug in Code:

app = FastAPI(debug=True)

Set the DEBUG environment variable before starting your FastAPI server:

DEBUG=true uvicorn main:app --reload

This command tells Uvicorn to start your FastAPI app with hot-reloading enabled.

Wrapping Up

Integrating Arel into your FastAPI project is a straightforward way to boost your development workflow with browser hot-reloading. No more tedious manual refreshes—just quick, automatic updates that let you focus on building awesome features.

Ready to give it a try? Check out the GitHub repository for a complete implementation and start enhancing your FastAPI development experience today!

Happy coding! 🚀

Top comments (0)