Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

FastAPI for AI Engineers - Part 10: Mastering FastAPI: Scaling with APIRouters and Background Tasks

说明与用途

使用 APIRouter 进行模块化路由简化 FastAPI 结构,BackgroundTasks 处理长时间 AI 任务而不阻塞客户端。

问题

Routing all endpoints through a single main.py file becomes unmaintainable as the project grows, leading to debugging nightmares.

结果

Modular routing with APIRouter reduces code complexity and improves maintainability, while BackgroundTasks decouple heavy AI processing from HTTP responses, preventing client timeouts.

工作流

  • Create routers directory and add auth.py, agents.py, tasks.py with APIRouter instances
  • Define route prefixes and tags in each router
  • Move endpoint definitions from main.py to respective router files using @router.get/post/etc.
  • In main.py, import routers and call app.include_router for each
  • Run FastAPI app and verify /docs shows organized endpoints
  • Define heavy AI processing function (e.g., simulate_ai_agent) that opens a new DB session
  • Inject BackgroundTasks into endpoint and add background_task(simulate_ai_agent, task_id)
  • Return a JSON response with status: queued immediately
  • Ensure frontend handles queued status and polls or receives updates

证据

routing every endpoint through a single main.py file creates an unmaintainable, thousands-of-lines-long bottleneck

来源

APIRouter as a mini-FastAPI instance. It allows you to split your endpoints across multiple files based on their domain

来源

FastAPI’s BackgroundTasks solves this by decoupling the HTTP response from the heavy computation

来源

  • 记录日期: 2026-10-26T15:26:24.717Z