Blog

Master Claude Code for FastAPI: Practical dev workflow guide

Goon Nguyen•Claude Code Guides••13 min read

Claude Code FastAPI: A practical development workflow

Using Claude Code for FastAPI speeds up route and test creation while maintaining your repository's existing conventions. This guide walks through configuring CLAUDE.md and implementing focused features safely - ensuring generated code remains reviewable while architecture and security decisions stay under your control.

Master Claude Code for FastAPI: Practical dev workflow guide

What Claude Code can do in a FastAPI project

Claude Code is a terminal-based coding agent that can inspect repositories, edit files, and execute permitted commands. In FastAPI projects, it can help with routes, schemas, services, tests, and configuration. Effective use requires narrow tasks, appropriate environment permissions, explicit acceptance criteria, and human review of the resulting changes.

Claude Code documentation describes these capabilities; actual access depends on your configured tools and permissions. The Claude Code CLI does not provide a native guarantee of FastAPI correctness.

Tasks Claude Code handles well

  • Repetitive scaffolding following existing repository patterns.
  • Request/response schemas and endpoint implementation.
  • Tests derived from explicit acceptance criteria.
  • Mechanical refactoring and execution of existing checks.

Tasks that still require developer judgment

Can assist

Requires approval

Authentication integration

Authorization design

Migration drafting

Data safety and rollback decisions

Dependency suggestions

Dependency selection

Async handler changes

Concurrency and blocking behavior

Test generation

Whether tests verify intended behavior

Risk identification

Production security decisions

For FastAPI backend development, treat generated work as a proposed change—not an approved engineering decision.

Master Claude Code for FastAPI: Practical dev workflow guide

Prepare the FastAPI repository before starting Claude Code

  1. Create a clean working branch and inspect existing changes.
  2. Confirm the app starts using its documented command.
  3. Record versions and the dependency manager.
  4. Identify the entry point and repository layout.
  5. Locate validation commands, including migrations when applicable.
  6. Run baseline checks and record existing failures.
  7. Request inspection without edits before implementation.

Example boundary: This article uses an illustrative, local-only tasks application—not an executed case study. Commands assume Python 3.11+, pip, FastAPI, Pydantic v2, Uvicorn, pytest, HTTPX, Ruff, and mypy in the active environment.

Minimum prerequisites

Complete Claude Code setup and authentication first. Use a Git repository, working Python environment, and configured tests. Keep credentials development-only; exclude production access and secrets.

For the assumed entry point app/main.py, containing app = FastAPI():

python -m uvicorn app.main:app --reload
# In another terminal, from the repository root:
claude

Record versions with python --version, claude --version, and python -m pip freeze. Save the commit identifier, baseline commands, and failures with your change notes.

Example FastAPI project structure

app/
__init__.py
main.py
api/tasks.py # HTTP handlers
schemas/tasks.py # Request/response models
services/tasks.py # Task operations
repositories/tasks.py # In-memory storage
tests/
test_tasks.py
pyproject.toml
CLAUDE.md

This FastAPI project structure is illustrative, not a restructuring requirement. Router → Service → Repository is one convention, not a FastAPI rule. Retain alembic/ only where migrations already exist.

First repository inspection prompt

Inspect without editing. Identify the entry point, architecture,
installed versions, storage, tests, and startup/validation commands.
List affected areas for POST /tasks and GET /tasks/{task_id}.
Report uncertainties and baseline failures. Propose a plan, then stop
for approval.

This instruction is not a security boundary. Restrict actual tools, credentials, and filesystem access separately.

Master Claude Code for FastAPI: Practical dev workflow guide

Create a FastAPI-specific CLAUDE.md file

A FastAPI CLAUDE.md supplies reusable project guidance. Claude Code documentation describes how instruction files enter context; they do not guarantee compliance or replace permissions, isolation, and review.

Keep instructions short enough to inspect and specific enough to verify.

Essential instruction categories

  1. Project overview.
  2. Architecture conventions.
  3. Python and FastAPI conventions.
  4. Pydantic version and schema rules.
  5. Database and session boundaries.
  6. Dependency injection patterns.
  7. Testing requirements.
  8. Validation commands.
  9. Scope restrictions and approval requirements.

Abbreviated CLAUDE.md example

Copy this template, then replace example assumptions with verified repository facts:

# Project guidance

- Follow existing repository patterns; avoid unrelated edits.
- Preserve request/response fields, status codes, and error conventions.
- Keep request/response schemas distinct from persistence models.
- Use the installed Pydantic version. For v2, preserve the project's
configuration, validation, and serialization conventions.
- Reuse FastAPI Depends() patterns where dependencies already exist.
- Example storage is process-local memory: no database or migration.
- In database-backed projects, preserve the established synchronous
or asynchronous SQLAlchemy pattern and session ownership.
- Request approval before dependencies, migrations, authentication,
authorization, or public-contract changes.
- Add behavior tests for changed endpoints and failure cases.
- Run documented checks. Report commands, outcomes, failures,
and checks not run. Never weaken assertions to obtain a pass.
- Stop when a fix would exceed approved scope.

# Completion
Acceptance criteria demonstrated; diff reviewed; limitations reported.
Use only validation commands confirmed for this repository.

Pydantic documentation distinguishes v2 configuration and serialization APIs from earlier versions. Do not impose v2 syntax on a repository using v1.

Likewise, Async SQLAlchemy is not an automatic upgrade: preserve synchronous database patterns unless a separate, reviewed change requires otherwise.

Instructions to avoid

  • Vague goals such as “make everything production-ready.”
  • Conflicting architecture rules.
  • Commands unavailable in the environment.
  • Broad rewrite permissions.
  • Copied documentation that hides project-specific guidance.

Use the template before your first feature, and confirm every stated convention against the repository.

Master Claude Code for FastAPI: Practical dev workflow guide

Build a FastAPI feature with Claude Code step by step

  1. Write acceptance criteria.
  2. Ask for a plan before editing.
  3. Implement the smallest complete change.
  4. Run a bounded feedback loop.
  5. Review against the original request.

This example uses process-local, in-memory storage. Tasks disappear on restart and are not shared between workers. There is no database migration or production persistence claim.

Step 1 - Write acceptance criteria

Define behavior before requesting API endpoint generation:

  • POST /tasks accepts a required string title with at least one character.
  • Successful creation returns 201 and exactly id and title.
  • id is a server-generated UUID, serialized as a string.
  • GET /tasks/{task_id} returns 200 with the stored task.
  • Missing, empty, or non-string titles return 422.
  • Malformed UUID paths return 422; unknown valid UUIDs return 404 with {"detail":"Task not found"}.
  • Preserve submitted titles; whitespace-only values are allowed in this minimal contract.
  • Add endpoint tests without new dependencies or unrelated modules.

For the assumed Pydantic v2 environment, the schema is:

from uuid import UUID

from pydantic import BaseModel, Field


class TaskCreate(BaseModel):
title: str = Field(min_length=1, strict=True)


class TaskRead(BaseModel):
id: UUID
title: str

The local example has no authentication. Do not expose it as a multi-user service. In an existing application, preserve authentication and test ownership restrictions explicitly.

Step 2 - Ask Claude Code for a plan before editing

Plan the tasks feature using the stated acceptance criteria.
List affected files, request flow, storage lifetime, assumptions,
migration implications, and endpoint tests. Preserve repository
conventions. Identify any missing prerequisite. Do not edit.
Wait for approval.

Reject unnecessary abstractions, unrequested upgrades, and additional endpoints. The proposed plan should explain router registration in app/main.py and how tests isolate in-memory state.

Step 3 - Implement the smallest complete change

Implement the approved plan. Allowed files:
app/main.py, app/api/tasks.py, app/schemas/tasks.py,
app/services/tasks.py, app/repositories/tasks.py, tests/test_tasks.py.
Reuse existing naming, dependency injection, error handling,
storage utilities, and fixtures. No dependency or configuration edits.
Stop if prerequisites or acceptance criteria require scope changes.

Request one complete create-and-retrieve path first. For larger changes, introduce checkpoints instead of approving an entire backend rewrite.

Step 4 - Make Claude run the feedback loop

These illustrative commands match the declared example tools and paths; adapt them to your repository’s documented configuration:

python -m ruff format app/api/tasks.py app/schemas/tasks.py app/services/tasks.py app/repositories/tasks.py app/main.py tests/test_tasks.py
python -m ruff check app tests
python -m mypy app
python -m pytest tests/test_tasks.py -q
python -m pytest -q

Formatting edits files, so inspect its diff. Endpoint tests using FastAPI’s TestClient exercise HTTP behavior; they are not pure unit tests of isolated functions. Require executed commands, pass/fail results, remaining failures, and skipped checks with reasons. Permit at most two in-scope correction attempts before reassessing. Stop sooner for dependency changes or expanded scope.

Step 5 - Review the result against the original request

Verify every criterion against actual responses and tests. Inspect the OpenAPI contract, unexplained file changes, dependency changes, and remaining risks. Do not merge solely because Claude reports success. Human approval closes the workflow.

Test and review Claude Code’s FastAPI changes

Generated tests can reproduce generated code’s mistakes. Derive expected results from the original contract-not from whatever the implementation happens to return.

For example, independently check that creation returns 201, not merely a successful status. Retrieve the returned identifier and assert both response fields. Reset storage between tests so execution order cannot hide defects.

Validation matrix

Validation layer

What it establishes and misses

Typical tool

Formatting

Formatting consistency, not behavior.

Ruff

Linting

Imports and configured static checks, not complete correctness.

Ruff

Typing

Type-contract issues within configured coverage.

mypy or Pyright

Tests

Asserted success, failure, and relevant authorization behavior.

pytest

API contract

Documented schemas/status codes plus actual response assertions.

FastAPI OpenAPI and endpoint tests

Database

Migration intent, data preservation, and session lifecycle; not applicable to this in-memory example.

Alembic/SQLAlchemy plus review

Security

Review of authorization, secrets, sensitive data, and input handling; no complete assurance.

Human review and project tooling

FastAPI documentation explains testing and OpenAPI generation. An OpenAPI document describes a contract; its existence does not prove runtime correctness.

Ruff and mypy documentation describe configurable checks. Excluded files and disabled rules limit coverage. Alembic documentation also requires reviewing autogenerated migrations rather than assuming they preserve data.

Human review questions before merge

  • Are scope and dependency changes approved?
  • Can responses expose sensitive data or bypass ownership checks?
  • In async code, are there blocking calls, missing await, session-lifetime issues, or unexpected lazy-loading I/O?
  • Do invalid input, missing resources, and permission failures behave correctly?
  • Are migrations safe and separately reviewed where applicable?
  • Is the code understandable without the original chat?

Run relevant checks again in CI (continuous integration). CI reproduces configured checks; it does not automatically perform security review.

Use this matrix as your review checklist. Passing local checks supports merge review, not production readiness, which additionally depends on the project’s release requirements.

Master Claude Code for FastAPI: Practical dev workflow guide

Refactor an existing FastAPI backend without losing control

Refactoring FastAPI with Claude should preserve behavior, not silently expand features.

  • Before: Inspect callers and capture existing responses. Characterization tests record current behavior before restructuring it. If that behavior includes a suspected bug, decide separately whether to preserve or change it.
  • During: Approve one structural change, such as extracting task lookup logic from a route into the existing service.
  • After: Compare responses, status codes, and side effects; run checks and inspect the diff.

Safe refactoring prompt

Inspect app/api/tasks.py, app/services/tasks.py, and their callers.
Document current lookup behavior and missing characterization tests.
Propose the smallest extraction into the existing task service.
Preserve response fields, status codes, errors, and storage behavior.
No upgrades, unrelated cleanup, or new abstractions.
Explain affected files and wait for approval before editing.

Common failure modes

These are possible risks, not findings from an executed demonstration.

Failure mode

Prevention

Broad rewrites

Approve one boundary at a time.

Duplicate utilities

Inspect existing helpers first.

Sync/async mixing

Preserve the established execution model.

Unsafe migrations

Require separate data-safety review.

Over-mocked tests

Retain meaningful endpoint coverage.

Weakened assertions

Compare tests against the original contract.

Dependency sprawl

Approve additions explicitly.

Architecture drift

Check existing boundaries in the diff.

When returning to earlier work, inspect the current repository again. Conversation context does not establish current file state.

Stop when behavior is unclear, public contracts would change, migrations risk data loss, or corrections exceed approved scope. Treat feature changes as a separate request, even when they appear convenient during refactoring.

Master Claude Code for FastAPI: Practical dev workflow guide

A repeatable Claude Code FastAPI workflow

Reuse the process, not the assumptions from a previous repository. A reusable FastAPI workflow should make approvals and evidence visible without accumulating unnecessary instructions.

  1. Establish a baseline.
  2. Inspect the repository.
  3. Define acceptance criteria.
  4. Review the plan.
  5. Approve limited scope.
  6. Run validation.
  7. Review the diff and unresolved risks.

FastAPI definition of done

Copy this FastAPI development checklist into your change description:

  • Acceptance criteria are demonstrated by meaningful assertions.
  • Changed files and dependencies remain within approved scope.
  • Required checks pass, or exceptions receive explicit review.
  • API behavior and applicable database changes are reviewed.
  • Security-sensitive behavior receives human review.
  • Commands, results, skipped checks, and limitations are documented.
  • Code is understandable without the original session.

Retain unresolved baseline failures in the record; do not relabel them as successful validation.

Optional reusable AgentKit setup

AgentKit is optional for this workflow. Its Engineer kit packages planning, tests-first implementation, and evidence-based review into reusable skills (for example, /ak:plan, /ak:cook, and /ak:code-review) that map to the steps above. Adapt them to your repository’s conventions and keep approval of scope, dependencies, and migrations with a human reviewer.

Frequently asked questions

What can Claude Code realistically do in a FastAPI project?

Claude Code acts as a terminal-based coding agent that inspects your repository, proposes file edits, and executes permitted commands. It excels at scaffolding FastAPI endpoints, generating Pydantic request/response schemas, and writing pytest suites, provided you define narrow tasks and perform careful human review of all changes.

Is CLAUDE.md a security enforcement tool for FastAPI?

No. CLAUDE.md is a guidance file for the agent, not a security boundary. While it helps Claude Code adhere to your project’s Pydantic version, database session patterns, and router conventions, it cannot prevent the agent from making mistakes. Always manually review security-sensitive code, migrations, and dependency changes.

Does Claude Code guarantee correct async SQLAlchemy implementation?

No. Claude Code follows the context it is given, so state your project’s established database pattern in CLAUDE.md, whether synchronous or asynchronous. Preserve that pattern rather than converting it, and review session lifetime, missing await, blocking calls, and lazy-loading I/O in async code.

How should I validate FastAPI changes generated by an agent?

Validation requires a multi-layer approach beyond simple execution. Run your configured ruff linting, type checkers like mypy, and focused endpoint tests with pytest. Finally, perform a manual diff review to ensure the generated code preserves existing architecture, handles edge cases like 404s/422s, and introduces no extraneous dependencies.

Can Claude Code safely refactor my existing FastAPI backend?

Yes, but only if you use a "characterization" approach. First, establish a baseline by creating tests that document current behavior. Then, request only behavior-preserving changes and approve the implementation plan before edits occur. Stop immediately if the refactor expands beyond your approved scope or requires new dependencies.

Follow this cycle: establish a tested baseline, inspect the repository, define clear acceptance criteria, review the implementation plan, approve a limited scope of work, execute automated validation checks, and perform a final human review of the diff and any remaining architectural risks.

Read more:

Conclusion

Reliable Claude Code development relies on clear repo rules and strict diff verification. Start with small, bounded changes on a feature branch, update your CLAUDE.md, and use the definition-of-done checklist to ensure architectural, security, and migration choices always receive human approval.

Share this article