Codex works well for FastAPI because the framework’s route/schema/dependency structure maps directly to small, reviewable code changes. Start codex in your project folder, keep instructions in AGENTS.md, and drive it with prompts that include the endpoint contract, file location, and test command. This guide covers a practical loop for CRUD endpoints, Pydantic models, async routes, and pytest with TestClient.
Why Codex fits FastAPI work
FastAPI apps tend to be explicit: path operations declare response models, dependencies are separate callables, and schemas live in Pydantic classes. Codex can read the existing pattern and extend it without architectural guesswork. A prompt like “add a GET /items/{item_id} endpoint following the style of items.py” usually produces a route, a schema lookup, and a test. The benefits are strongest when the project has strict conventions, because the agent can imitate them. See Codex for agent basics and How to use Codex CLI: a step-by-step guide for a CLI workflow primer. Use Codex for localized FastAPI work rather than asking it to redesign the whole application at once.
Setting up the project for Codex
Put a short AGENTS.md in the repository root. Codex reads it before acting, so treat it as the source of truth for build, test, lint, and project rules. For FastAPI, do not just list generic commands; include the import style, router structure, response model rules, and the TestClient pattern.
# AGENTS.md
## Commands
- Install: `pip install -e ".[dev]"`
- Run API: `uvicorn app.main:app --reload`
- Test: `pytest -q`
- Lint: `ruff check .`
- Format: `ruff format .`
## Conventions
- Application code lives in `app/`, tests in `tests/`.
- Routers go in `app/routers/` and are included from `app/main.py`.
- Pydantic schemas live in `app/schemas.py`; separate `*Create`, `*Update`, and `*Response` models.
- Endpoints must declare `response_model` in the decorator and return Pydantic models or dicts that match it.
- Use `async def` for endpoints that await I/O; use plain `def` for CPU-bound or synchronous ORM work.
- Dependencies live in `app/dependencies.py` and are named `get_*`.
- Add a `tests/test_*.py` file with `TestClient` for every new endpoint.
- Run `pytest -q` after each change; do not leave failing tests.
| Path | Purpose |
|---|---|
app/main.py | FastAPI instance and router includes |
app/routers/ | Path operations |
app/schemas.py | Pydantic request and response models |
tests/test_*.py | TestClient-based endpoint tests |
Keep the rules specific. If your project uses SQLModel or SQLAlchemy, state that response_model must be a Pydantic schema, not an ORM object. If you use async sessions, say where get_session lives and whether endpoints should use it directly. A file under 80 lines is easier for Codex to follow than a long policy document.
A working loop for FastAPI changes
Work in small increments: ask for one endpoint, model, or dependency at a time. After each change, run the tests, read the diff, and look for schema or import mistakes before committing. A good prompt names the route, the input/output shape, the file, and the test command.
Example prompts for typical FastAPI work:
- Add a
POST /usersendpoint inapp/routers/users.pythat accepts aUserCreatePydantic model, inserts a row with SQLAlchemy, and returns aUserResponse. Add a test totests/test_users.pywithTestClientthat asserts the response and status code. - Create a
get_current_userdependency inapp/dependencies.pythat reads theAuthorizationheader, raises 401 when missing, and returns a placeholder user. Apply it toGET /me. - Change
PUT /items/{item_id}to return a 404 with{"detail": "item not found"}when the item does not exist. Update the existing test, then runpytest -q. - Write tests for
POST /logincovering invalid payload, unknown user, wrong password, and success. UseTestClientand keep each case in a separate test function. - Refactor repeated pagination query parameters into a reusable dependency. Update all list endpoints and run the full test suite.
What Codex handles well and where to watch closely
Codex is reliable for CRUD path operations, Pydantic schemas, dependency stubs, OpenAPI-facing response_model fixes, and test generation. It often catches missing imports and decorator arguments when the prompt includes the existing style. Watch closely on:
- Pydantic v1/v2 differences:
class Configversusmodel_config,orm_modeversusfrom_attributes. The agent may mix versions. - Returning ORM objects: FastAPI does not serialize SQLAlchemy objects unless
from_attributes=Trueor you convert to a Pydantic schema. - Dependencies with state: yield dependencies, request-scoped services, and cleanup must not be replaced with module-level globals.
- Async blocking: code may insert a synchronous DB call or
requests.getinside anasync defendpoint, which blocks the event loop. - Lifecycle and TestClient: moving startup logic to lifespan can break tests that relied on
@app.on_event. - Security: if you ask for auth, verify it is actually applied to every new route, not just the first one.
Treat large refactors as separate prompts with tests as a safety net.
Testing and verification with Codex
For FastAPI, TestClient is the quickest way to verify route behavior without running a server. Keep tests in tests/ and instruct Codex to run the relevant file before and after a change. Example commands: pytest -q tests/test_users.py, then pytest -q. Ask the agent to update tests when it changes a response model or status code; do not accept a code change that leaves old assertions.
When reviewing a generated test, check that it asserts the response JSON, status code, and validation errors explicitly, not just that the request succeeds. If the project uses coverage, run pytest --cov=app --cov-report=term-missing after a batch of changes and review uncovered lines with the agent. For larger changes, use AI code review: check what your agents write to add a second-model review pass, which can catch FastAPI-specific issues like a wrong response_model or a blocking call in an async path operation.
Running several agents on one FastAPI project with AgentVera
For FastAPI teams, AgentVera’s parallel worktrees matter most: one agent can add a users router while another fixes auth in app/dependencies.py without overwriting files. The automatic code review catches framework-specific mistakes such as returning ORM objects or missing response_model, with findings linked to file:line. Checkpoints let you undo a bad refactor of Pydantic schemas or dependency wiring in one click. Token budgets prevent an agent from burning through a full test suite run while keeping its conversation for remediation.
Wrap-up
Codex is most useful in a FastAPI project when you constrain it with AGENTS.md, small prompts, and a fast test loop. Keep the agent focused on one route or schema at a time, require pytest with TestClient after each change, and review diffs for Pydantic and async mistakes. Used that way, codex becomes a reliable pair programmer for API development without the usual context thrash.