# Using Claude Code with FastAPI: A Practical Guide

URL: https://agentvera.dev/en/blog/claude-code-for-fastapi/ · Published: 2026-11-01

Learn how to set up Claude Code for FastAPI projects, write a useful CLAUDE.md, prompt for endpoints, schemas, and tests, and verify changes safely.

**In short:**

- Put build, test, and FastAPI conventions in CLAUDE.md so Claude Code follows your project rules.
- Use small, test-driven steps: prompt for one endpoint or schema change, run pytest, review the diff.
- Watch async dependencies and Pydantic validation closely; Claude Code is fast but needs verification.

[Claude Code](/en/agents/claude-code/) is a terminal coding agent that runs inside your FastAPI project when you launch `claude`. It can read route files, modify Pydantic schemas, write tests, and run pytest. To get reliable results, give it a strict project context and verify each change before letting it continue.

## What makes Claude Code a good fit for FastAPI

FastAPI code is heavily structured around a few moving parts: path operations, Pydantic models, dependency injection, and async endpoints. Claude Code reads Python imports and type hints well, which means it can follow a router include, see the schema used as `response_model`, and keep the contract consistent. Because FastAPI relies on type annotations for validation and documentation, the agent can use those annotations to make safer edits than in untyped Python projects. It also works naturally with TestClient-based pytest suites. Rather than generating whole apps from scratch, it is most effective when asked to change one endpoint, schema, dependency, or test at a time. That matches how FastAPI projects evolve in practice.

## Preparing your FastAPI project for Claude Code

Start in the project root and create CLAUDE.md. The file should be short but explicit. Include exact commands so the agent does not guess the test or lint runner. Specify the module layout and the FastAPI-specific rules you enforce: Pydantic v2 model config, always use `response_model`, keep session dependencies out of path operations, and prefer `async def` only where the endpoint awaits I/O. A minimal example:

```markdown
# CLAUDE.md

## Commands
- Install: `uv sync`
- Run API: `uv run uvicorn app.main:app --reload`
- Test: `uv run pytest -q`
- Lint: `uv run ruff check app tests`
- Format: `uv run ruff format app tests`

## Project layout
- `app/main.py`: FastAPI application, router includes
- `app/routers/`: path operations grouped by resource
- `app/schemas/`: Pydantic models for requests/responses
- `app/services/`: business logic, async where I/O bound
- `app/dependencies.py`: reusable `Depends` callables
- `tests/`: pytest files using `TestClient`

## FastAPI rules
- Use Pydantic v2 style: `model_config = ConfigDict(from_attributes=True)`
- Every write path returns a `response_model`, not a dict
- Use `async def` for endpoints that await I/O; keep CPU-bound work in sync defs
- Put database/session logic in dependencies, not in path operations
- Tests must hit the API through `TestClient`, not call service functions directly
```

Keep rules factual, not aspirational. If you use `Annotated` for dependencies, say so. If you require `from __future__ import annotations`, note it. The agent uses CLAUDE.md as the first source of truth, then looks at existing code. For broader agent habits, see [Claude Code best practices: a practical checklist](/en/blog/claude-code-best-practices/).

## A practical workflow: plan, edit, test, review

Work in small steps: select a route or schema, describe the expected behavior, let Claude Code propose a diff, review it, run the focused tests, then commit or reject. Use plan mode for changes that touch multiple files; the [plan mode guide](/en/blog/claude-code-plan-mode/) explains how to get a plan before code changes. Typical prompts for FastAPI work:

- Add a `POST /users` endpoint that takes `UserCreate`, returns `UserRead`, and includes a test with valid and invalid payloads.
- Change the existing `GET /items` endpoint to accept `limit` and `offset` as `Query` parameters with `ge=1` and `le=100`, and update the test.
- Refactor database access out of `routers/tasks.py` into an async dependency in `dependencies.py`, then run pytest.
- Convert `GET /reports` to use an async session dependency and ensure the TestClient tests still pass without blocking calls.
- Review the last diff for Pydantic v2 config mistakes and missing response models.

After each prompt, require the agent to run the relevant test file, not the entire suite initially. If the diff is larger than expected, reset and ask for a smaller change. This loop prevents the agent from rewriting a working router while adding one field.

## Where Claude Code excels and where to watch closely

FastAPI tasks that usually go well: adding CRUD endpoints, updating Pydantic schemas and tests together, adding dependency overrides for tests, converting sync endpoints to async when the dependency is async, and generating OpenAPI-aware validation tests. Watch closely on these FastAPI-specific failure modes:

- It may mix Pydantic v1 and v2 syntax: `.dict()` instead of `.model_dump()`, or `orm_mode = True` instead of `from_attributes = True`.
- It might add `async def` to an endpoint that only calls a sync database function, adding no benefit and sometimes complicating the event loop.
- It may change the dependency injection graph implicitly, for example returning a new object from `Depends` and breaking downstream dependencies.
- It can alter the `response_model` shape or default status code without updating the OpenAPI-dependent tests.
- It sometimes over-engineers: adding middleware, routers, or service layers when a path operation function would do.

## Verifying FastAPI changes with tests

Testing with Claude Code works best when the prompt ties code and tests to the same contract. For a new endpoint, ask for the path operation, the Pydantic schema, and a TestClient test in the same turn. Then ask the agent to run `pytest -q tests/test_users.py` and fix only failures related to the change. Use the table below for common verification needs.

| Verification need | Prompt for Claude Code |
|-------------------|------------------------|
| Endpoint contract | Run pytest and add a test that asserts POST /users returns the UserRead schema for valid input. |
| Validation errors | Add a test with missing required fields and assert the 422 response includes the correct Pydantic error path. |
| Dependency behavior | Using dependency overrides in TestClient, test the auth dependency returns 401 when the token is invalid. |

After a green test run, ask the agent to show the diff and explain any changes in `app/dependencies.py` or `app/main.py`. FastAPI mistakes often hide in the dependency wiring, not the route function. For asynchronous code, make sure the test uses `TestClient` correctly; the agent may write direct `asyncio.run` calls instead of client requests, which bypasses the dependency injection and middleware. For dependency overrides, ask for tests that cover both the override and the real dependency path.

## Parallel FastAPI work with AgentVera

For larger FastAPI projects, AgentVera runs multiple Claude Code agents side by side, each in its own terminal panel. Each agent can work in its own git worktree, so one can refactor dependency injection while another adds a new router without overwriting files. Automatic code review after an agent turn catches FastAPI-specific mistakes such as missing `response_model`, incorrect Pydantic config, or broken dependency overrides, and findings link to file:line. Checkpoints let you undo a turn that introduced a Pydantic regression, while token budgets stop a long pytest-run loop from consuming the entire plan.

## Final thoughts

Claude Code is most useful on a FastAPI project when you treat it as a fast pair programmer that must prove every change with tests. Put the build, test, and schema rules in CLAUDE.md, keep prompts small, and review the dependency wiring before accepting a diff. The goal is not to generate the entire API in one shot, but to move endpoint by endpoint with passing pytest coverage.

## Frequently asked questions

**Can I use Claude Code with an existing FastAPI project?** Yes. Run claude in the project root after adding a CLAUDE.md that describes your commands and FastAPI conventions. It will read the existing routers, schemas, and tests before making changes.

**What should I put in CLAUDE.md for a FastAPI project?** Include the exact install, test, and lint commands, the folder structure, and FastAPI rules such as using Pydantic v2 config, always returning response models, and keeping database access in dependencies. Keep it short and factual.

**How do I get Claude Code to write correct async endpoints and dependency injection?** Prompt for one endpoint or dependency at a time and mention the expected async behavior. Ask for a TestClient test that calls the API, then review the dependency graph before accepting the diff.

**Can Claude Code run pytest and fix failing FastAPI tests?** Yes. Ask it to run the relevant test file such as pytest -q tests/test_users.py and fix only failures related to the current change. This keeps the loop focused and avoids unrelated rewrites.

---

**About AgentVera.** AgentVera is a desktop app for macOS, Windows and Linux, built by Solviera Teknoloji. It runs 18 AI coding agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor, Antigravity, opencode, Hermes, Qwen Code, Kimi Code, Kiro, Amp, Droid, Goose, Vibe, Crush, Aider, Cline) side by side, per project, in real terminals with the user's own CLI installs and logins. The free plan has unlimited agents. Download: https://agentvera.dev/en/download/ · Pricing: https://agentvera.dev/en/pricing/
