Creating boilerplate structure for FastAPI
The user is looking for a boilerplate for a Python FastAPI project that integrates with Celery and Redis. They likely want a structured file layout and key files, possibly including Docker and requirements. A typical boilerplate includes project structure, minimal examples of endpoints for triggering Celery tasks, and Redis configuration. I plan to outline a project structure with files like pyproject.toml or requirements.txt, main app, Celery instance, tasks, and possibly Docker Compose.Developing a usable boilerplate
I want to create a practical boilerplate for the user that strikes a balance between detail and usability. Including environment variables via a .env file and using pydantic-settings could be good, but I’m cautious about adding complexity. I plan to keep the configuration minimal and based on the environment, like getting REDIS_URL. Integrating Celery with FastAPI should involve creating a separate module. I’ll outline the necessary files like requirements.txt, main.py, and potentially include a docker-compose.yml for added convenience.Configuring Celery and project structure
I need to set up the configuration for Celery 5+, which includes defining the Celery app with Redis as the broker and backend. I’ll create sample tasks and set up FastAPI routes to trigger those tasks. For instance, I can create an "add" task. I’ll also include a route to check the task's status. The project’s file structure should consist of essential files like main.py, celery_app.py, and tasks.py, along with optional files for running a worker or Docker setup.Building and running the project
I'm excited to outline the commands necessary for running the project. First, I’d show how to install the dependencies with pip install -r requirements.txt. Then, for running the FastAPI app, I’d explain using uvicorn app.main:app --reload to enable live reloading. For launching the Celery worker, I'd provide the command celery -A app.celery_app.celery_app worker --loglevel=info. Additionally, I'll mention starting Redis with Docker using docker run -p 6379:6379 redis:7, but I’ll keep everything minimal and to the point!Crafting Celery and FastAPI integration
I'll set up the requirements.txt with essential libraries like FastAPI, Uvicorn, Celery, and Redis. In the app/celery_app.py, I'll define the Celery app with the Redis URL, configure task routes, and set a result expiration time. For tasks, I’ll create a simple add function with a delay.
In app/main.py, I’ll define FastAPI routes, including health checks and task creation. Optionally, I can include a basic docker-compose.yml, but since the user didn’t request Docker setup, I’ll keep it minimal and focus on the local run. Here’s a minimal but complete boilerplate for a FastAPI project using Celery with Redis as broker and result backend.
Project structure
fastapi-celery-redis/
├── app
│ ├── __init__.py
│ ├── celery_app.py
│ ├── main.py
│ └── tasks.py
├── requirements.txt
└── README.md (optional)
requirements.txt
fastapi
uvicorn[standard]
celery[redis]
redis
Install:
pip install -r requirements.txt
app/init.py
# Empty is fine, just makes "app" a package.
app/celery_app.py
import os
from celery import Celery
# You can override this with an environment variable in production
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
celery_app = Celery(
"worker",
broker=REDIS_URL,
backend=REDIS_URL,
include=["app.tasks"], # Where Celery will look for tasks
)
# Basic Celery configuration
celery_app.conf.update(
task_routes={
"app.tasks.*": {"queue": "default"},
},
result_expires=3600, # 1 hour
task_serializer="json",
result_serializer="json",
accept_content=["json"],
timezone="UTC",
enable_utc=True,
)
app/tasks.py
import time
from .celery_app import celery_app
@celery_app.task(name="app.tasks.add")
def add(x: int, y: int) -> int:
"""Example long-running task."""
time.sleep(5) # Simulate work
return x + y
app/main.py
from fastapi import FastAPI
from celery.result import AsyncResult
from .celery_app import celery_app
from .tasks import add
app = FastAPI(title="FastAPI + Celery + Redis Boilerplate")
@app.get("/health")
def health_check():
return {"status": "ok"}
@app.post("/add")
def create_add_task(a: int, b: int):
"""
Trigger an asynchronous Celery task.
Usage: POST /add?a=1&b=2
"""
task = add.delay(a, b)
return {"task_id": task.id}
@app.get("/tasks/{task_id}")
def get_task_status(task_id: str):
"""
Check the status (and result) of a Celery task by ID.
"""
result = AsyncResult(task_id, app=celery_app)
return {
"task_id": task_id,
"status": result.status,
"result": result.result if result.ready() else None,
}
Running everything
1. Start Redis
If you have Docker:
docker run -d --name redis -p 6379:6379 redis:7
Or use a local Redis installation and adjust REDIS_URL if needed.
2. Start the FastAPI app
From the project root:
uvicorn app.main:app --reload
FastAPI will be available at http://127.0.0.1:8000.
3. Start the Celery worker
In another terminal (from the project root):
celery -A app.celery_app.celery_app worker --loglevel=info -Q default
Testing the setup
-
Trigger a task:
curl -X POST "http://127.0.0.1:8000/add?a=3&b=4"
Response:
{
"task_id": "some-uuid-here"
}
-
Check task status:
curl "http://127.0.0.1:8000/tasks/some-uuid-here"
You’ll see "PENDING", "STARTED", "SUCCESS", etc., and when done:
{
"task_id": "some-uuid-here",
"status": "SUCCESS",
"result": 7
}
If you’d like a Docker/Docker Compose-based boilerplate for the same setup, say so and I’ll add that as well.