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

opencode with FastAPI: a practical developer guide

Learn how to use the opencode coding agent in a FastAPI project: AGENTS.md setup, practical prompts, testing with TestClient, pitfalls, and parallel agents.

Solviera Teknoloji 6 min read

opencode is the coding agent described at opencode. Start it in the project root with opencode, keep the work in small, reviewable steps, and give it project rules in AGENTS.md. This guide covers the setup, prompts, testing, and pitfalls that matter for FastAPI work.

Why opencode fits FastAPI development

FastAPI projects are tightly coupled across a few layers: path operations call dependencies, dependencies return database sessions, Pydantic models validate request and response bodies, and tests override those dependencies. A good coding agent fits this shape because a change is rarely confined to one file. opencode reads the whole repository, so when you ask for a new endpoint it can add the route, import the schema, reuse the existing dependency, and update the test file without you having to paste file paths. That removes much of the mechanical work in FastAPI development, especially repetitive CRUD routers, schema migrations, and TestClient coverage.

Configuring AGENTS.md for a FastAPI project

opencode reads project instructions from AGENTS.md. Put that file in the repository root and keep it specific: commands, folder conventions, and FastAPI rules the agent should always follow. Do not write paragraphs of generic advice; the file should look like a checklist an experienced FastAPI developer would leave for a new teammate.

Create AGENTS.md with something like:

# AGENTS.md

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

## Layout
- app/main.py creates the FastAPI app and mounts routers.
- app/api/ holds path operations grouped by resource.
- app/schemas/ holds Pydantic request and response models.
- app/services/ holds business logic; never import FastAPI here.
- app/deps.py holds shared dependencies such as get_db and get_current_user.

## FastAPI rules
- Keep path operations thin: parse input, call a service, return a schema.
- Use Pydantic v2 models with model_config = ConfigDict(from_attributes=True) for ORM responses.
- Always set response_model on endpoints unless returning Response.
- Prefer async endpoints only when the database driver or client is async.
- Use dependency overrides in tests instead of monkeypatching globals.
- Run pytest -q before finishing; a task is done only when all tests pass.

Customize the commands for your package manager and test runner. pytest -q is the gate; if you use coverage, add pytest -q --cov=app after the main command. The layout section keeps opencode from placing a router in the wrong package. The FastAPI rules are most important because they prevent common agent mistakes such as missing response_model, returning ORM objects without from_attributes, or overriding dependencies in the wrong test scope.

A practical opencode workflow for FastAPI changes

The loop is: plan a single change, ask opencode for that change only, let it edit and run pytest -q, review git diff, and then commit or ask for a fix. FastAPI work splits naturally into small tasks. Start with the endpoint or schema, verify tests, then move to the next layer.

Example prompts for common FastAPI tasks:

  • Add a GET /users/{user_id} endpoint in app/api/users.py that returns UserRead from the database using the existing get_db dependency. Raise 404 if the user is missing.
  • Split UserCreate into UserCreate and UserUpdate: make email optional in update, keep password required on create, and update the register endpoint.
  • Convert POST /orders to async and use an async SQLAlchemy session dependency. Update the route and the order service, and run the order tests.
  • Add a get_current_user dependency that reads the Bearer token, verifies it, and returns the current user. Apply it to all routes under /me.
  • Write pytest tests for the items router using TestClient and app.dependency_overrides with a fake repository. Cover list, create, and 404.

Each prompt names files and behaviors, which keeps the agent from improvising architecture. After each task, have it run pytest -q and show the diff. If a test fails, ask for a targeted fix rather than a large rewrite. If the basic agent workflow itself is new, see How to use opencode: a step-by-step guide.

FastAPI tasks and where opencode needs supervision

opencode does well with mechanical FastAPI changes that require consistent multiple-file edits: adding CRUD endpoints, changing Pydantic schemas and the affected tests, adding dependencies, and moving logic into services. The risk areas are mostly FastAPI-specific behavior that a model can get subtly wrong.

TaskStrong promptWatch closely
Add a resource endpointAdd POST /items with ItemCreate and ItemRead; use get_db; return 201.Missing response_model, wrong status code, returning an ORM object without from_attributes.
Change a Pydantic schemaMake email optional in UserUpdate but keep it required in UserCreate.The agent may edit the wrong model or forget to update tests and OpenAPI examples.
Convert sync to asyncMake the route and database call async; use AsyncSession; update tests.Mixing sync and async sessions, or using a sync dependency in an async route.
Add a dependencyAdd get_current_user from the bearer token and apply it to /me routes.Caching of Depends, import cycles, and whether the dependency should yield or return.
Write or update testsUse TestClient and app.dependency_overrides to replace the repository.Overrides leaking across tests; missing lifespan; asserting data before response model conversion.

Watch Pydantic v2 defaults: the agent may use Field(default=...) and response_model_exclude_unset incorrectly. Watch route order: a fixed prefix such as /users/me must be declared before /users/{user_id}. Watch dependency yields: if the agent changes a dependency to yield, ensure cleanup runs and the test override replaces the same dependency object. Use git diff to check for changes to more files than the task requires.

Testing FastAPI changes with opencode and TestClient

Let opencode run pytest -q after every task, but do not accept changes only because tests pass. For FastAPI, tests often pass while the OpenAPI contract or runtime behavior is wrong. Verify response_model fields, status codes, and dependency overrides manually in the diff. A useful extra check is to ask the agent to add a test that asserts the OpenAPI schema contains the new path and expected response model; TestClient can expose app.openapi().

When an endpoint returns an ORM object, confirm the Pydantic response model has from_attributes=True or the code returns a schema instance. When tests use app.dependency_overrides, check that the override is set in a fixture or before the client call and cleared afterward. Run only the affected test file first, then the full suite. If you have a TestClient lifespan, run the full suite because startup events may fail only in combination.

Parallel opencode agents on one FastAPI repo with AgentVera

For larger FastAPI projects, AgentVera lets you run several opencode sessions side by side in real terminal panels. The most useful features are per-agent git worktrees, so one agent can add a schema while another writes tests for a router without overwriting files; automatic code review after each turn, which catches FastAPI issues such as missing response_model or a dependency override that leaks; and token budgets, which stop an agent from looping on a failing pytest run. Checkpoints also let you undo a bad dependency refactor in one click. For a deeper look at this approach, see Best tools to run AI coding agents in parallel (2026).

Final thoughts

opencode is most productive on FastAPI when you treat it as a junior contributor with full repo access: give it a clear AGENTS.md, one small task at a time, run pytest after each step, and inspect every diff. The agent can handle the repetitive route-schema-test cycle, but FastAPI-specific behavior around dependencies, response models, and async sessions still needs your review. With that loop, opencode reduces the mechanical work and leaves more time for API design.

Questions

How do I start opencode on a FastAPI project?

Run opencode in the project root; it reads AGENTS.md from that directory. Before starting, add a short AGENTS.md with your test, lint, and run commands, plus FastAPI rules such as using response models and dependency overrides. Then give it a small task, such as adding one endpoint or changing one Pydantic model.

Can opencode run pytest and fix failing FastAPI tests?

Yes. Ask it to run pytest -q after a change and fix the specific failing test. It can read the traceback, edit the route, service, or schema file, and rerun the tests. Review the diff before accepting, especially around dependency_overrides and response_model mismatches.

Does opencode understand FastAPI dependency injection?

It understands the common patterns when they are visible in the repo: Depends, app.dependency_overrides, and yield dependencies. The safest approach is to keep shared dependencies in a single deps.py and tell the agent in AGENTS.md to reuse them. Watch for accidental import cycles and dependency caching.

How can I keep several opencode agents from overwriting each other’s files in one FastAPI project?

Use AgentVera or git worktrees to give each agent its own working copy. For FastAPI work, assign non-overlapping areas such as one router, one schema set, or one test module per agent. Merge worktrees only after each agent’s tests pass.

Bring your agents to one desk.

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

More opencode guides

Other agents for FastAPI