# Gemini CLI and FastAPI: a practical workflow for devs

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

Use Gemini CLI on FastAPI projects: set up GEMINI.md, prompt for routes, schemas, dependencies, and verify safely with pytest, TestClient, and lint.

**In short:**

- Gemini CLI reads GEMINI.md and can edit FastAPI routers, Pydantic schemas, dependencies, and tests in one cohesive change.
- Keep tasks small, run pytest and ruff after each change, and review the diff to catch validation, async, and DI mistakes.
- When parallelizing FastAPI work, use a separate git worktree per agent so changes do not overwrite each other.

[Gemini CLI](/en/agents/gemini-cli/) is a terminal coding agent that can read your whole FastAPI repository and make coordinated changes across routers, schemas, dependencies, and tests. Start it with `gemini` in the project folder, keep a concise GEMINI.md at the repository root, and use the loop below to keep changes reviewable. This guide focuses on realistic FastAPI workflows: path operations, Pydantic models, dependency injection, async endpoints, and pytest with TestClient.

## Why Gemini CLI fits FastAPI development

FastAPI projects have a predictable shape: an app factory or main module, routers, Pydantic schemas, and dependency functions. Gemini CLI is effective here because it can hold that structure in context while editing multiple files at once. For example, changing a response model often means updating a schema, a router import, a service return type, and a test expectation; the agent can do all four in one small diff.

It also handles the repetitive parts well: adding standard error responses, converting sync handlers to async def where I/O is involved, and writing parametrized pytest cases. The value is not in generating code from scratch, but in making small, verified increments across a codebase that already has conventions. Keep tasks narrow so the agent does not refactor unrelated code or introduce circular imports.

## Preparing the project: what to put in GEMINI.md

The most important file is GEMINI.md at the repository root. It tells the agent how to build, test, lint, and where code lives. For FastAPI, include explicit rules that prevent the most common mistakes. A realistic minimal file:

```markdown
# GEMINI.md
Project: FastAPI service for user and order management.

Commands:
- install: python -m pip install -e ".[dev]"
- test: python -m pytest -q
- lint: python -m ruff check app tests
- run: uvicorn app.main:app --reload

Layout:
- app/main.py: create FastAPI instance and include routers.
- app/routers/: path operations only, no business logic.
- app/schemas.py: Pydantic v2 models for requests and responses.
- app/deps.py: dependency injection functions.
- app/services.py: business logic.
- tests/: pytest files using TestClient.

Rules:
- Use async def for endpoints that perform I/O; use sync def only for pure CPU work.
- Always set response_model on decorators unless returning a Response object.
- Use Pydantic v2 syntax: model_validate, model_dump, field_validator.
- Dependencies are functions, not classes, and are imported from app.deps.
- Never create a new router without registering it in app.main.
- Before declaring a task done, run pytest and ruff and show the output.
```

Keep the file short enough that the agent does not ignore it. Update it when you add a new router or change test commands. For more on the general workflow, see [How to use Gemini CLI: a step-by-step guide](/en/blog/how-to-use-gemini-cli/).

## A repeatable workflow: plan, edit, test, review

Treat the agent as a junior FastAPI developer with strong Python skills but no memory between sessions. Use this loop:

1. Plan: name the endpoint, schema, or bug and the files that should change.
2. Small step: ask for one coherent change, not a feature branch.
3. Run tests: tell the agent to run `python -m pytest -q` and `python -m ruff check app tests` after the edit.
4. Review the diff: look at imports, dependency injection, and response_model before merging.
5. Iterate: feed any failure or review comment back to the agent.

Example prompts that work well for FastAPI tasks:

- Add a `GET /users/{user_id}` endpoint that returns `UserOut` and raises 404 when missing. Put the route in `app/routers/users.py` and add a pytest with `TestClient`.
- Create a `create_order` Pydantic schema and a `require_api_key` dependency. Use them in an async `POST /orders` endpoint, and write tests for missing and invalid API keys.
- Refactor the existing orders router to call functions from `app/services.py` instead of doing database work inline. Keep the public response shape unchanged and update tests only where necessary.
- Fix the failing test in `tests/test_auth.py` without changing the public API. Explain the dependency injection error before editing.
- Add a `GET /health` endpoint that returns `{"status":"ok"}` only after a startup check for the database, and test both healthy and unhealthy states.

## Where Gemini CLI excels in FastAPI and where it stumbles

Gemini CLI is strong at adding standard CRUD endpoints, converting payloads between Pydantic schemas and ORM objects, and writing table-driven tests. It is less reliable when it has to guess project-specific conventions or when a change touches many routers at once.

| Task | Good prompt | Watch closely |
| --- | --- | --- |
| Add a JSON POST endpoint | Add `POST /items` with `ItemCreate` and `ItemOut`, async def, response_model=ItemOut. | It may skip response_model or use sync def and block the event loop. |
| Add dependency injection | Add `get_current_user` from app.deps and require it on the profile route. | It may create circular imports between routers and deps, or use `Depends` in a non-route helper. |
| Pydantic validation | Add a `field_validator` to normalize emails before storing. | It may use Pydantic v1 decorators like `@validator` or call `.dict()` instead of `model_dump()`. |
| Test a route | Write a pytest for `PATCH /users/{user_id}` using TestClient and dependency_overrides. | It may overmock dependencies and not test status codes or response shape; it may also forget to restore overrides. |

Review any new dependency injection because a wrong `Depends` signature often passes tests but fails at runtime. Watch for sync endpoints that call `await` or async endpoints that call blocking I/O without `run_in_threadpool`. If a change touches Pydantic schemas, run a quick check that all `response_model` imports still resolve before accepting the diff.

## Testing FastAPI changes with the agent

Require the agent to run the test suite after every change. Use `python -m pytest -q` as the default command and make it show the full traceback on failure. For FastAPI, prefer tests built around `TestClient` because they exercise the actual routing, middleware, and exception handlers. Direct unit tests of service functions are useful, but they do not catch wrong status codes or missing response models.

Tell the agent to use `app.dependency_overrides` when a route depends on a database session or an external client. For example, override `get_db` with a fixture that yields a session around a test database. Do not accept a test that patches the function body but never sends an HTTP request; that gives false confidence.

After a green test run, ask the agent to run a linter such as `python -m ruff check app tests`. If you use type checking, run `mypy app` only if it is already part of the project. Review the diff for test-only changes that weaken assertions, such as changing `assert response.status_code == 201` to `assert response.status_code in (200, 201)` just to make a failing test pass.

## Running parallel agents on a FastAPI project with AgentVera

AgentVera runs real CLI tools such as Gemini CLI side by side in real terminal panels, which helps when a FastAPI project has several independent workstreams. Each agent can work in its own git worktree, so one can add an orders router while another fixes auth without overwriting files. When an agent’s turn ends, a second model reviews its code and links findings to file:line, which catches FastAPI-specific mistakes such as a missing `response_model` or an incorrect `Depends` signature. Checkpoints snapshot each turn, so a bad refactor of Pydantic schemas can be undone in one click. For more on coordinating agents, see [AI agent orchestration for coding: 5 patterns and tools](/en/blog/ai-coding-agent-orchestration/).

## Final thoughts

Gemini CLI works well as a FastAPI pair programmer when you give it a clear GEMINI.md, request small changes, and enforce tests and linting before merge. The main risk is not the agent writing Python, but it silently changing conventions such as Pydantic v1 syntax, blocking the event loop, or miswiring dependency injection. Keep the review loop tight, and if you run several agents, isolate them in separate worktrees so FastAPI routers and schemas stay consistent.

## Frequently asked questions

**How do I start Gemini CLI in an existing FastAPI project?** Run gemini in the project root, then make sure a GEMINI.md file exists with your test command, lint command, and folder conventions. Ask it to read the file and the relevant FastAPI modules before making changes. It works best when you keep the first task small and run the test suite afterward.

**What should I put in GEMINI.md for a FastAPI service?** Include package manager, test, lint, and run commands, plus the project layout and rules such as using async def for I/O, Pydantic v2 model_dump instead of .dict(), and response_model on path operations. Also tell it where routers, schemas, and dependencies live.

**Can Gemini CLI write or update pytest tests with FastAPI’s TestClient?** Yes, it can generate pytest files that use TestClient and dependency_overrides. Ask it to run the tests after writing them and to include assertions for status codes, response shape, and validation errors.

**How do I prevent Gemini CLI from breaking async endpoints or Pydantic models?** Keep changes small, put explicit rules in GEMINI.md, and review the diff for sync def endpoints that block the event loop or Pydantic v1 syntax. Require pytest and ruff to pass before accepting a change, and ask the agent to explain any dependency injection changes.

---

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