# Cursor Agent FastAPI: Practical Setup and Testing

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

Learn how to use Cursor Agent on a FastAPI project: setup with AGENTS.md, practical prompts, pytest verification, and safe parallel agent workflows.

**In short:**

- Cursor Agent reads AGENTS.md or .cursor/rules, so explicit FastAPI commands and conventions keep it productive.
- Work in small slices: one endpoint, model, or dependency plus a pytest test, then run tests and review the diff.
- For parallel work, use separate git worktrees and rely on code review and checkpoints to avoid FastAPI-specific mistakes.

[Cursor Agent](/en/agents/cursor-agent/) is well suited to FastAPI work because it can read the full project, edit path operations and Pydantic models, run the test suite, and show the diff before you commit. Start it in the project folder with `cursor-agent` after you add project instructions. This guide covers a practical setup, a working loop, testing, and parallel use.

## FastAPI work that fits Cursor Agent

FastAPI code is repetitive in a good way: routers, response models, dependencies, and HTTPException branches follow the same shapes. Cursor Agent can generate these patterns consistently once it sees your conventions. It also runs `pytest` and `ruff` in the terminal, so it can catch a missing `status_code`, a Pydantic validation mismatch, or an async/sync mismatch before you do. Because FastAPI relies on runtime behavior such as dependency injection and response serialization, an agent that only edits files is not enough; Cursor Agent can execute the actual tests and read the tracebacks.

## Project instructions for FastAPI

Create an `AGENTS.md` at the project root or use `.cursor/rules` with the same content. Keep it short, concrete, and FastAPI-specific. Do not instruct the agent to write clean code; tell it exactly which commands to run, where routers and schemas live, and which Pydantic or async conventions to follow.

```markdown
# AGENTS.md

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

## Layout
- `app/main.py` creates the FastAPI app and includes routers.
- `app/routers/` contains one APIRouter per resource.
- `app/schemas/` contains Pydantic v2 models.
- `app/deps.py` contains shared dependencies.

## FastAPI rules
- Use Pydantic v2 style: `model_config = ConfigDict(from_attributes=True)` when returning ORM objects.
- Use `response_model=` on path operations; do not return raw SQLAlchemy objects.
- Put reusable logic in dependencies with `Depends`.
- Write async endpoints only when they call async code; keep sync endpoints as plain `def`.
- Always add `status_code=` explicitly for create and delete endpoints.
- Tests use `fastapi.testclient.TestClient`; each test must be independent.
```

If the agent seems to ignore these rules, a more detailed walkthrough is available in [how to use Cursor CLI](/en/blog/how-to-use-cursor-cli/).

## Working loop and example prompts

Work in small slices: plan one endpoint, model, or dependency at a time; let the agent implement it; run the full test suite; then review the diff. Do not ask for a complete auth system in one prompt. The loop should be:

1. State the route or model precisely, including request/response schema and status code.
2. Ask for a pytest test in the same change.
3. Run `pytest -q` and `ruff check app tests`.
4. Review the diff for accidental changes to `main.py`, requirements, or unrelated routers.
5. If a test fails, paste the traceback and ask for a minimal fix.

Example prompts that fit this loop:

- Add a `GET /items/{item_id}` endpoint that returns an `ItemOut` Pydantic model, accepts an integer path parameter, and raises `HTTPException(404)` when the item does not exist.
- Create a `POST /items` endpoint with request body `ItemCreate`, response model `ItemOut`, and explicit `status_code=201`; add a happy-path test and a 422 validation test.
- Refactor the current-user lookup in `app/routers/users.py` into a reusable dependency with `Depends`, then update the three routes that use it.
- Write a pytest file using `TestClient` that covers `GET /health`, `GET /v1/version`, and a 404 fallback route.
- Run `pytest -x`, read the failures, and fix only the code under `app/routers/orders.py`; do not modify tests to make failures disappear.

For a broader safe workflow around this loop, see [how to vibe code safely](/en/blog/how-to-vibe-code/).

## Strengths and pitfalls by task

Cursor Agent is effective at adding path operations, updating response models, extracting dependencies, and writing targeted pytest coverage. A task-to-prompt table helps keep the work focused.

| FastAPI task | Prompt that keeps the agent focused |
|---|---|
| New path operation | Add `GET /users/{user_id}` returning `UserOut`, with 404 for missing rows. |
| Response model fix | Change `PATCH /invoices/{id}` to accept optional `InvoiceUpdate` and return the updated `InvoiceOut` without leaking internal fields. |
| Shared dependency | Create a `get_tenant_id` dependency from the `X-Tenant-ID` header and add it to all billing routes. |
| Test coverage | Add pytest cases for `POST /auth/login`: one 200, one 401, one 422 with a short password. |

Watch closely when the agent handles Pydantic v1/v2 differences, especially `orm_mode` versus `from_attributes` and `@validator` versus `@field_validator`. It may return SQLAlchemy models directly, so they fail at serialization despite a green test. It may add `async def` to endpoints that only run sync code, which FastAPI will still run in a threadpool but the mix can confuse later readers. It may forget `response_model` on create or update routes, losing response validation and OpenAPI accuracy. It may duplicate logic instead of using dependencies. Review those spots in every diff.

## Testing FastAPI changes with pytest

Make the agent verify with the real test client, not just eyeball the code. Use `fastapi.testclient.TestClient` with a fixture that creates a clean app and test database. Good prompts ask for both positive and negative tests and for the agent to run them. For each change, require that `uv run pytest -q` passes, `uv run ruff check app tests` passes, the diff does not modify tests just to hide failures, and the agent shows a representative 200 and 422 response from the test client or a local run. This catches response model mistakes and dependency injection regressions before they reach code review.

## Running several agents with AgentVera

FastAPI projects often have several independent routers, so you can scale up by running multiple agents in parallel with [AgentVera](/en/blog/best-tools-parallel-ai-coding-agents/). Each agent works in its own git worktree, so one can add an orders endpoint while another refactors auth without overwriting files. When an agent’s turn ends, a second model reviews the code and links findings to file:line, which is valuable for catching FastAPI `response_model` or dependency mistakes. Checkpoints let you undo a turn if a migration or router change breaks the test suite, and token budgets stop an agent from turning a small endpoint into a broad refactor.

## Final notes for FastAPI work

Cursor Agent becomes predictable on a FastAPI project when you put explicit AGENTS.md rules in place and keep the work in small, testable slices. Start with one router, require pytest coverage, and review the diff before accepting changes. If you need more throughput, run separate agents in their own worktrees and use review and checkpoints to keep the codebase safe.

## Frequently asked questions

**How do I start Cursor Agent in a FastAPI project?** Open the project directory in a terminal and run cursor-agent. It reads instructions from AGENTS.md or .cursor/rules, so create those files first with your FastAPI commands and conventions.

**What should I put in AGENTS.md for a FastAPI project?** Include concrete commands like pytest and ruff, the folder layout for routers and schemas, and rules such as always using Pydantic response models, explicit status codes, and dependencies instead of duplicated logic. Keep it specific and short.

**Can Cursor Agent write and run FastAPI tests?** Yes. It can create pytest files using TestClient and run the suite to read failures. Review any changes to tests to ensure the agent is not changing assertions just to make failures disappear.

**How do I run several Cursor Agents on one FastAPI project without conflicts?** Run each agent in its own git worktree or use a parallel agent tool like AgentVera. The worktree approach keeps file changes isolated until you review and merge them, preventing one agent from overwriting another’s work.

---

**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/
