It seems that the user likely wants full code, so I plan to include an explanation of the project structure along with the code for each file and minimal instructions on how to run things, like installing dependencies and starting services.
I might mention optional containerization but avoid unnecessary details about Celery theory. I'm aiming for a clean design, including the project tree and providing a simple configuration setup. I'll also keep in mind the potential version differences in Pydantic.Creating a simple configuration
I'm contemplating a simple approach without using an environment library; just using os.getenv. However, it might be better to follow good practices with a dataclass.
So, I can create a Settings class using BaseSettings with CELERY_BROKER_URL and CELERY_RESULT_BACKEND. I'll set the .env file in the configuration.
Now, regarding dependencies, I'll list fastapi, uvicorn, celery, redis, and pydantic, keeping in mind the changes with Pydantic v2. I’ll aim for a setup that works well moving forward.Streamlining Celery tasks
To keep things simple and avoid confusion, I'll focus on a straightforward setup. I'll make sure users install pydantic-settings in the requirements.
For the Celery configuration, we can set things like the timezone and content types, but I'll skip many optional settings for brevity. In tasks.py, I’ll define a task called add_numbers that takes two integers and adds them after a brief pause.
I could use the shared_task decorator, but for now, I'll keep it simple and use the direct task method. I’ll ensure that we avoid circular imports by structuring the imports carefully between celery_app.py and tasks.py.Deciding on task discovery method
I’ve realized that Celery’s autodiscovery uses importlib internally, but since there’s no direct import from celery_app to tasks, it relies on loading strings like app.tasks. They need to be importable, but not at the top level to avoid circular dependencies.
Celery will import tasks lazily, which is good news! We might not need autodiscovery if we directly import the tasks module, but I think keeping autodiscovery simplifies things. So, I will use the shared_task decorator in tasks.py, creating a clean pattern that avoids circular imports.Structuring the FastAPI project
Alright, let’s set up the main FastAPI application. I’ll import necessary packages, including BaseModel from Pydantic and AsyncResult from Celery. The app will define an endpoint for adding numbers and checking task status.
I’ll ensure that my Celery configuration is ready, including Redis as both the broker and result backend. For the dependencies in requirements.txt, I’ll list FastAPI, Uvicorn, Celery, Redis, and pydantic-settings.
I'll provide detailed instructions for running the application, including how to set up a virtual environment and start relevant services. Finally, I’ll mention an optional Docker Compose setup for convenience while keeping things concise. Here’s a minimal but complete boilerplate for a FastAPI project using Celery with Redis as broker and result backend.
from celery import shared_task
import time
@shared_task(name="app.tasks.add")
def add(x: int, y: int) -> int:
# Simulate a long-running computation
time.sleep(5)
return x + y
app/main.py
python
from typing import Any, Optional
from fastapi import FastAPI
from pydantic import BaseModel
from celery.result import AsyncResult
from app.celery_app import celery_app
from app.tasks import add
app = FastAPI(title="FastAPI + Celery + Redis Boilerplate")
class AddRequest(BaseModel):
x: int
y: int
class TaskStatusResponse(BaseModel):
task_id: str
status: str
result: Optional[Any] = None
@app.post("/tasks/add", response_model=TaskStatusResponse)
async def create_add_task(body: AddRequest):
"""
Enqueue a task that adds two numbers.
"""
task = add.delay(body.x, body.y)
return TaskStatusResponse(task_id=task.id, status=task.status)
@app.get("/tasks/status/{task_id}", response_model=TaskStatusResponse)
async def get_task_status(task_id: str):
"""
Get status (and result, if finished) for a given Celery task.
"""
task_result = AsyncResult(task_id, app=celery_app)
result: Any = None
if task_result.successful():
result = task_result.result # The return value of the task
elif task_result.failed():
# Optional: you may want to serialize exceptions differently
result = str(task_result.result)
return TaskStatusResponse(
task_id=task_id,
status=task_result.status,
result=result,
)
If you’d like, I can extend this boilerplate with Docker/Docker Compose files, Flower for monitoring Celery, or a more modular project layout (routers, services, separate settings for environments).