Backend · Skill

Build a FastAPI backend

build-fastapi-backend

Scaffolds a production-ready Python API with FastAPI - a clear folder layout, Pydantic models, settings from environment variables, dependency injection for the database and auth, async routes and a first pytest suite. Use when the user wants a Python backend, a FastAPI project, a REST API or server in Python, or to tidy a messy FastAPI app.

Works with: Any AI Not yet model-tested; testing Jan 2027

Paste it into ChatGPT, Claude, Gemini or any AI chat, then tell it about your project. How it works

Install in Claude Code, Cursor or Codex (optional)

Only for AI coding tools that read skill folders. Run one line in a terminal, in your project folder. It downloads this skill's text files from TheSkillVault and nothing else; you can read them first with “View raw SKILL.md”.

Claude Code (all your projects)

curl -fsSL --create-dirs 'https://theskillvault.ai/api/skills/build-fastapi-backend/raw' -o ~/'.claude/skills/build-fastapi-backend/SKILL.md' && curl -fsSL --create-dirs 'https://theskillvault.ai/api/skills/build-fastapi-backend/files/LICENSE.txt' -o ~/'.claude/skills/build-fastapi-backend/LICENSE.txt'

Cursor (this project)

curl -fsSL --create-dirs 'https://theskillvault.ai/api/skills/build-fastapi-backend/raw' -o '.cursor/skills/build-fastapi-backend/SKILL.md' && curl -fsSL --create-dirs 'https://theskillvault.ai/api/skills/build-fastapi-backend/files/LICENSE.txt' -o '.cursor/skills/build-fastapi-backend/LICENSE.txt'

Codex and other Agent Skills tools (this project)

curl -fsSL --create-dirs 'https://theskillvault.ai/api/skills/build-fastapi-backend/raw' -o '.agents/skills/build-fastapi-backend/SKILL.md' && curl -fsSL --create-dirs 'https://theskillvault.ai/api/skills/build-fastapi-backend/files/LICENSE.txt' -o '.agents/skills/build-fastapi-backend/LICENSE.txt'

Or connect the whole library over MCP

Add TheSkillVault to Cursor or add this to your app's MCP settings (read-only; help):

{
  "mcpServers": {
    "theskillvault": {
      "url": "https://theskillvault.ai/mcp"
    }
  }
}

FastAPI gives you a typed Python API with automatic docs at /docs. Start small and keep each layer in its own folder.

When to use

  • You want a backend in Python rather than JavaScript.
  • You need a REST API for a web or mobile front end.
  • Your FastAPI app has grown into one big main.py.

Steps

  1. Create a project with a virtual environment (or uv init) and install fastapi, uvicorn[standard], pydantic-settings and pytest plus httpx.
  2. Use this layout:
app/
  main.py        # creates the app, includes routers
  config.py      # Settings read from env vars
  api/           # one router file per resource
  models/        # database models
  schemas/       # Pydantic request and response models
  services/      # business logic, no HTTP code
tests/
  1. Read settings with pydantic-settings from environment variables and a git-ignored .env.
  2. Write request and response schemas first. Never return database objects straight to the client.
  3. Add a database session as a dependency with Depends(get_db), so tests can swap it.
  4. Add auth as a dependency too (Depends(current_user)), and use it on every private route.
  5. Use async def routes with an async driver, or plain def with a sync one. Do not mix them in one call path.
  6. Raise HTTPException with clear status codes, and add one handler for unexpected errors.
  7. Write tests with TestClient or httpx.AsyncClient and override dependencies for the database.
  8. Run with uvicorn app.main:app --reload and check /docs.
@router.get("/items/{item_id}", response_model=ItemOut)
async def read_item(item_id: int, db: Session = Depends(get_db), user: User = Depends(current_user)):
    item = await items.get_for_user(db, item_id, user.id)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

Gotchas

  • Calling a blocking library inside async def freezes the whole server. Use an async client or a sync route.
  • Keep .env out of git and never print the database password or API keys in logs.
  • Lock CORS to your front-end origins; allow_origins=["*"] with cookies is a security hole.
  • Use migrations (Alembic) for schema changes, not create_all in production.

Portability

Works with Postgres, SQLite or MySQL through SQLAlchemy or SQLModel. If you use Django or Flask instead, the same split of schemas, services and dependencies still applies.

Example prompt

"Set up a FastAPI backend with users and items, settings from env vars, auth on private routes and pytest tests."

Done when

  • /docs shows every route with request and response schemas.
  • Settings come from the environment; no secrets in code.
  • Private routes reject requests without auth.
  • pytest passes with the database dependency overridden.

---

Adapted from "fastapi-templates" in wshobson/agents (MIT, Copyright (c) 2024 Seth Hobson). See LICENSE.txt.

Bundled files

Licence

Adapted from Seth Hobson (wshobson/agents, fastapi-templates) (Copyright (c) 2024 Seth Hobson), MIT License. Adapted by TheSkillVault: rewritten as a beginner build order with a smaller layout and short original code; dropped the long templates and repository-pattern examples; added secrets handling, gotchas and done-when.

Licence: MIT License. Attribution when you reuse it: Based on work by Seth Hobson (wshobson/agents, fastapi-templates) (Copyright (c) 2024 Seth Hobson, MIT License), https://github.com/wshobson/agents/tree/7e2fb559cf4b824b27f1fec49fe88f7511066d26/plugins/api-scaffolding/skills/fastapi-templates; adapted by TheSkillVault, https://theskillvault.ai