# Add OpenAPI Docs to a chi API

Yes. An agent describes a chi API's routes and types in OpenAPI, serves it with Swagger UI, checks it against the running server in its sandbox and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-openapi-docs/chi/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent maps the API from the router before writing a line of specification. In a service laid out like dhax/go-base, `api/api.go` builds a `chi.Mux` with `Recoverer`, `RequestID`, a `Timeout` of fifteen seconds, structured logging, `render.SetContentType` and optional CORS, mounts `/auth` from the passwordless package (`POST /login`, `/token`, `/refresh`, `/logout`), puts `/admin` and `/api` behind `jwtauth`'s verifier and `jwt.Authenticator`, answers `/healthz`, and serves the single-page app from `/*`. `api/app/account.go` exposes `GET`, `PUT` and `DELETE` on `/api/account` and `PUT` and `DELETE` on `/api/account/token/{tokenID}`, with an `accountRequest` type that embeds `pwdless.Account` and shadows its protected fields; `api/app/profile.go` has a get and an update; `api/admin/accounts.go` lists, creates, gets, updates and deletes under `/admin/accounts/{accountID}`; `errors.go` in each package defines the `render.Renderer` error bodies. `cmd/gendoc.go` already generates `routes.md` with `go-chi/docgen`, a Markdown listing of middleware chains whose links point at a `vendor/` directory that no longer exists, so the only documentation of the routes is stale. `go.mod` says Go 1.25 and chi v5.4.0 while `.tool-versions` says 1.18, and `.github/workflows/main.yml` runs lint, `go test -v ./...` and a `CGO_ENABLED=0` build.

The handlers and types exist, so the agent documents them where they are with `swaggo/swag` annotations: a `@Summary`, `@Tags`, `@Param`, `@Success` and `@Failure` block above each handler, naming the request type and the error renderers from `errors.go` for the status codes each handler returns, a `@securityDefinitions` block for the bearer JWT with `@Security` on every `/admin` and `/api` route and none on `/auth/login`, and the general information in a comment above `main`. A `//go:generate` line runs `swag init` so the generated `docs/` package is a build artefact produced by one command rather than by hand, and it is committed so a clone has it. `http-swagger` mounts the UI at `/swagger/*` in `api.go`, which chi matches ahead of the `/*` catch-all for the single-page app.

Documentation that nobody checks drifts the way `routes.md` did, so the agent adds a step to the lint workflow that runs the generator and fails on `git diff --exit-code docs/`, which makes a handler change without its annotation a red check. It leaves `gendoc` and `routes.md` in place and notes the stale links in the pull request rather than removing a command the request did not mention.

In its sandbox the agent installs PostgreSQL from apt because `database.DBConn()` needs one at start, copies `.env.example` to `.env` with a local `AUTH_JWT_SECRET`, runs `go run main.go migrate` and `go run main.go serve`, fetches `/swagger/doc.json`, validates it with an OpenAPI validator, and compares it with the server: `/healthz` and `/auth/login` with a bad body return what the spec says, and a request to `/api/account` without a token gets the 401 body the `@Failure` line names. It runs `go test ./...`, `go vet` and golangci-lint so the comment blocks pass the lint the CI runs.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add OpenAPI documentation to this chi API. Read api/api.go, every file under api/app/, api/admin/ and auth/, cmd/gendoc.go, routes.md, main.go, go.mod, .tool-versions, .env.example and the workflows under .github/ first. Annotate each handler with swaggo/swag comments naming its request and response types and the error renderers it returns, define the bearer JWT security scheme and apply it to the routes behind the authenticator, and add a go:generate line that produces the docs package, committed. Serve Swagger UI from the router ahead of the single-page-app catch-all. Add a CI step that regenerates the docs and fails when the committed copy differs. Do not remove the existing routes.md generator; note that its links are stale. In the sandbox, install PostgreSQL, run the migrations and the server, fetch the generated spec, validate it, and compare the health, login and unauthenticated account responses with what the spec says. Run go test, go vet and golangci-lint. Open a pull request whose description quotes the validator output and the comparisons.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds annotation blocks above the handlers in `api/app/`, `api/admin/` and `auth/pwdless/`, a generated `docs/` package, the Swagger UI mount in `api/api.go`, a `go:generate` line and a workflow step. `routes.md` and `cmd/gendoc.go` are untouched. The description quotes the validator's result on `/swagger/doc.json`, the three comparisons between the running server and the spec, and the `go test` and lint output, and it points out the stale `vendor/` links in `routes.md` and the disagreement between `.tool-versions` and `go.mod`.

The run's record keeps the server log, the fetched spec and each comparison request, so a reviewer can read the exact 401 body the server returned next to the `@Failure` line that documents it.

Before merging, a reviewer checks the request examples against the `accountRequest` shadowing, since the protected `id`, `active` and `roles` fields appear in the type but are ignored on write, decides whether the UI should be served in production or only behind a flag, and confirms the generated package is excluded from coverage.

## Run it on every Linear issue labelled api-docs

In the console, add an automation to the Project with a `linear` trigger on `linear.issue.labeled` and the label `api-docs`, with this prompt. When someone files an issue asking for a reference for a service and labels it, the run starts with the issue as its context, makes the change in the Project's repository and opens a pull request on its own branch linked to the issue. A label added by an app integration never fires the trigger, and the automation starts at most `max_runs_per_hour` runs in an hour.

To start it from a support tool instead, send this body to `POST /o/{org}/sessions` with the issue text appended to the prompt and a `request_id` that is a UUID v5 of the issue id, so a retried delivery returns the run already started.

## Why run it on Rush?

An OpenAPI description written from the code without running the code documents what the author believes the handlers do. The error bodies, the fields a request silently ignores, the routes the catch-all swallows: these show only when the server answers. In a Rush sandbox the agent starts the database and the server, fetches the generated spec and compares real responses against it before the pull request exists.

The spec, the validator's verdict and the comparison requests stay with the run, so the reviewer reads the server's answer beside the line that documents it. Several services run in parallel, each in its own sandbox with its own database and its own pull request, and each check in CI keeps its own spec from drifting.

## Frequently asked questions

### Why annotations instead of a hand-written spec?

The handlers, request types and error renderers already exist in the code, and a spec written beside them drifts the moment a handler changes, the way `routes.md` did. Annotations sit on the handler, the generator reads the types, and the CI step fails when the committed output is out of date.

### Does the generated package need to be committed?

Yes, so a clone serves the UI without running the generator first and so the CI diff check has something to compare. The `go:generate` line is the one way to change it.

### Will the UI route conflict with the single-page app?

No. chi matches `/swagger/*` before the `/*` catch-all that serves the app, and the sandbox run confirms both answer. A reviewer can put the mount behind a configuration flag if the UI should not ship to production.

### What happens to routes.md and the gendoc command?

They stay. The request is OpenAPI, and removing a command is its own decision. The pull request says the Markdown's links point at a `vendor/` directory that no longer exists so the team can retire it deliberately.

### Why does the sandbox need PostgreSQL?

Because `api.New` opens the database and the mailer before it builds the router, so the server cannot start without one. Installing it locally in the sandbox is what lets the agent compare real responses with the spec instead of only generating a file.

## More chi jobs

- [Add OpenTelemetry Tracing to a chi API](https://getrush.ai/run/add-opentelemetry/chi/)
- [Add Prometheus Metrics to a chi API](https://getrush.ai/run/add-prometheus-metrics/chi/)
- [Add Rate Limiting to a Go chi API](https://getrush.ai/run/add-rate-limiting/chi/)

## The same job on other stacks

- [Add OpenAPI Docs to a Django REST Framework API](https://getrush.ai/run/add-openapi-docs/django-rest-framework/)
- [Serve OpenAPI Docs from a Fastify API from a Linear Issue](https://getrush.ai/run/add-openapi-docs/fastify/)
- [Add OpenAPI Docs to a Fiber App](https://getrush.ai/run/add-openapi-docs/fiber/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
