Invite a friend, get 1 month of Pro freeHow it works

Codex FastAPI: Practical Agent Workflow for REST APIs

Learn a practical Codex workflow for FastAPI: AGENTS.md setup, prompts for endpoints and tests, pitfalls to avoid, and multi-agent runs.

Solviera Teknoloji 5 min read

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.
PathPurpose
app/main.pyFastAPI instance and router includes
app/routers/Path operations
app/schemas.pyPydantic request and response models
tests/test_*.pyTestClient-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 /users endpoint in app/routers/users.py that accepts a UserCreate Pydantic model, inserts a row with SQLAlchemy, and returns a UserResponse. Add a test to tests/test_users.py with TestClient that asserts the response and status code.
  • Create a get_current_user dependency in app/dependencies.py that reads the Authorization header, raises 401 when missing, and returns a placeholder user. Apply it to GET /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 run pytest -q.
  • Write tests for POST /login covering invalid payload, unknown user, wrong password, and success. Use TestClient and 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 Config versus model_config, orm_mode versus from_attributes. The agent may mix versions.
  • Returning ORM objects: FastAPI does not serialize SQLAlchemy objects unless from_attributes=True or 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.get inside an async def endpoint, 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.

Questions

Can Codex create a complete FastAPI endpoint from a prompt?

Yes, when your AGENTS.md defines the project conventions. Give Codex the route, request/response Pydantic models, file location, and test command; it can add the path operation, schema, dependency, and TestClient test in one pass.

What should AGENTS.md contain for a FastAPI project?

List the install, run, test, and lint commands; folder layout; router and schema conventions; response model rules; async versus sync guidance; and a rule to add a test for every new endpoint. Keep it short and specific to your stack.

How do I get Codex to run tests automatically?

Include the test command in AGENTS.md and end prompts with an instruction such as 'run pytest -q tests/test_users.py after the change'. Codex can run the command and use failures to adjust the code.

Does Codex understand async FastAPI endpoints and dependency injection?

It understands the syntax and common patterns, but should be watched on blocking calls in async endpoints and stateful dependencies. Explicitly mention where dependencies live and whether endpoints use async sessions.

Bring your agents to one desk.

Download AgentVera for free; your installed CLIs are ready to go.

More Codex guides

Other agents for FastAPI