# Add OpenAPI Docs to a Rocket API

Yes. An agent documents your Rocket routes with the rocket_okapi release matching your pinned Rocket, serves openapi.json and Swagger UI, tests it and opens a PR.

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

## What the agent does

The agent reads the version pins before anything else, because for Rocket the documentation crate has to match the framework release exactly. In an API like TatriX/realworld-rust-rocket, `Cargo.toml` depends on `rocket` at `0.5.0-rc.1` with only the `json` feature, `rocket_sync_db_pools` at `0.1.0-rc.1` with `diesel_postgres_pool`, `rocket_cors`, `diesel` 1.4 with `postgres` and `chrono`, `validator` and `validator_derive`, `jsonwebtoken`, `scrypt` and `dotenv`; `Cargo.lock` confirms `rocket 0.5.0-rc.1`, and `rust-toolchain` says `nightly`, which `src/lib.rs` needs for `#![feature(proc_macro_hygiene, decl_macro)]`. `lib.rs` mounts nineteen handlers under `/api` with `routes![]`, attaches `database::Db::fairing()`, a CORS fairing and `config::AppState::manage()`, and registers a 404 catcher. The handlers in `src/routes/` return `Result<Value, Errors>`, where `Errors` in `src/errors.rs` is a responder that answers 422 with `{"errors": {field: [code]}}`, and request bodies are `Json<NewUser>`, `Json<LoginUser>` and the article and comment wrappers with `#[derive(Deserialize, Validate)]` fields. `src/auth.rs` is a request guard that reads `Authorization: Token <jwt>` by the `TOKEN_PREFIX` in `src/config.rs` and fails with 403, and `Option<Auth>` marks the routes that work anonymously. `tests/common.rs` builds a shared `Client::tracked(realworld::rocket())` and logs in through `/api/users/login`; `.travis.yml` is the only CI and runs `cargo test` against a Postgres it seeds with `init.sql` and `diesel migration run`.

The pin decides the crate. On crates.io, `rocket_okapi 0.8.0-rc.1` declares `rocket ^0.5.0-rc.1`, so it resolves against this lock as it stands; `0.8.0-rc.2` and `0.8.0-rc.3` pin `=0.5.0-rc.2` and `=0.5.0-rc.3`, and `0.9.0` pins `=0.5.1`, each of which would force a Rocket upgrade first. The agent adds `rocket_okapi` at `0.8.0-rc.1` with the `swagger` feature and `schemars`, replaces `routes![]` in `lib.rs` with `openapi_get_routes![]`, puts `#[openapi(tag = "Users")]`, `Articles`, `Profiles` and `Tags` on each handler, and mounts `make_swagger_ui` at `/swagger-ui/` with the config pointing at `../openapi.json`. Every request and response type gets `#[derive(JsonSchema)]`, including the private `NewUserData` and `LoginUserData` structs, so the body schemas show `username`, `email` and `password` with their `Validate` rules in the description.

Two guards need to be explained to the document. `Db` from `rocket_sync_db_pools` is not a request header, so it gets an `OpenApiFromRequest` implementation that returns `RequestHeaderInput::None`; `Auth` gets one that declares an `apiKey` security scheme in the `Authorization` header with the `Token ` prefix, applied to every route that takes `Auth` and marked optional where the handler takes `Option<Auth>`. `Errors` gets an `OpenApiResponderInner` implementation so each route lists the 422 body shape, and the 403 from the guard is listed on the authenticated routes. Because the handlers return `serde_json::Value`, the response schemas are untyped; the agent documents that honestly as a 200 with a JSON object and lists, in the pull request, the `Json<T>` return types that would give typed responses as a follow-up rather than rewriting nineteen handlers now.

Then it builds and tests on nightly. The sandbox has no Docker, so the agent installs Postgres, runs `psql -f init.sql`, installs `diesel_cli` with the `postgres` feature and runs `diesel migration run` with the `.env` URL, then `cargo build` and `cargo test`. It adds `tests/openapi.rs` using the shared `test_client()`: a request to `/api/openapi.json` parsed as JSON, asserting that `paths` holds `/users/login`, `/articles/{slug}` and `/profiles/{username}/follow`, that `components.schemas` holds the user and article bodies, and that the security scheme is present; and a request to `/swagger-ui/` that answers HTML. It opens the UI in its own browser and executes the login example once against the seeded database to check the body the document describes is the one `post_users_login` accepts. It notes that `.travis.yml` is the only CI and that `CHANGELOG.md` has an empty `Unreleased` section, and adds a line there.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add OpenAPI documentation to this Rocket API. Read Cargo.toml, Cargo.lock, rust-toolchain, src/lib.rs, src/errors.rs, src/auth.rs, src/config.rs, every file under src/routes and src/models, tests/common.rs, .env, init.sql and .travis.yml first. Check on crates.io which rocket_okapi release declares a rocket requirement the locked Rocket version satisfies, and add that release with the swagger feature plus schemars; do not upgrade Rocket. Replace routes! with openapi_get_routes!, annotate each handler with openapi and a tag, derive JsonSchema on every request and response type, implement OpenApiFromRequest for the database and auth guards with an apiKey scheme in the Authorization header using the Token prefix, implement the error responder's OpenAPI responses for the 422 body, and mount Swagger UI at /swagger-ui/ reading ../openapi.json. Install Postgres in your sandbox, seed it with init.sql and the Diesel migrations, build on the pinned nightly, add a test that fetches /api/openapi.json and checks the paths, schemas and security scheme and that /swagger-ui/ answers, run cargo test, open the UI in your browser and execute the login example once, and open a pull request with the results and the typed response types you left as a follow-up.",
  "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

A pull request that changes `Cargo.toml` and `Cargo.lock` (the two crates), `src/lib.rs` (the route macro and the Swagger mount), every file under `src/routes/` and `src/models/` (attributes and derives), `src/auth.rs`, `src/database/mod.rs` and `src/errors.rs` (the three trait implementations), adds `tests/openapi.rs`, and adds a `CHANGELOG.md` line. The description names the `rocket_okapi` release and why, lists the paths and schemas the document contains, shows the `cargo test` output on nightly, and lists the handlers whose responses are untyped `Value` with the `Json<T>` change that would type them.

A reviewer checks the security scheme matches how clients really send the token, confirms the optional auth is marked only on the routes that take `Option<Auth>`, and merges. The API then serves `/api/openapi.json` and `/swagger-ui/` from the same binary, with no generator step and no second source of truth for the routes.

## Run it on every terminal hand-off

A developer who has just been asked for an API reference by a frontend team starts this from the terminal with this body and the repository in `resources`, and goes back to the feature they were on. The run reads the real pins and the real guards, so the document crate is the one that compiles against the lock and the security scheme is the header the guard actually parses.

Send a `request_id`, a UUID, with the body so a retried start returns the run it already began. When the turn ends, `GET /o/{org}/sessions/{id}` names the pull request, and a follow-up to the same session can ask for the typed `Json<T>` responses on the user routes, or for RapiDoc beside Swagger UI.

## Why run it on Rush?

On Rocket the first question is a version table, and getting it wrong costs an afternoon of dependency errors on nightly. The agent checks the registry, builds on the pinned toolchain with a real Postgres, and keeps every command and the generated document in the run's record, so the pull request shows the document the server serves and the tests that read it rather than a plan to add them.

The same run fits any Rocket service: one on Rocket 0.5 stable where `rocket_okapi 0.9` is the match, one using `rocket_db_pools` where the guard implementation differs, or one with typed `Json<T>` responses where every schema comes out typed on the first pass. Each gets the crate its lock admits and a test that fetches its own document.

## Frequently asked questions

### Why not upgrade Rocket and use the latest rocket_okapi?

Because the locked Rocket is a release candidate and the newer `rocket_okapi` releases pin exact later Rocket versions, an upgrade is a separate change with its own risks across every handler and the database pool crate. The run documents the API as it is and names the upgrade as the next step if the team wants it.

### Why are the response schemas untyped?

The handlers return `serde_json::Value` built with `json!`, so there is no Rust type to derive a schema from. The document says each success is a JSON object, which is true, and the pull request lists the `Json<T>` return types that would make them precise, since that touches every handler and deserves its own review.

### How is the token documented?

As an `apiKey` scheme in the `Authorization` header, with a description that the value is `Token ` followed by the JWT, matching `TOKEN_PREFIX` in `src/config.rs`. Routes that take `Auth` require it; routes that take `Option<Auth>` list it as optional.

### Does the test need a database?

The shared test client in `tests/common.rs` ignites the full rocket, including the Diesel pool fairing, so it needs the Postgres from `.env`. The run seeds one in its sandbox the way `.travis.yml` does, and the new test reads the document through that same client.

## More Rocket jobs

- [Add Prometheus Metrics to a Rocket App](https://getrush.ai/run/add-prometheus-metrics/rocket/)
- [Add Rate Limiting to a Rocket API](https://getrush.ai/run/add-rate-limiting/rocket/)
- [Add Request ID Logging to a Rocket App](https://getrush.ai/run/add-request-id-logging/rocket/)

## The same job on other stacks

- [Add OpenAPI Docs to a Slim 4 App](https://getrush.ai/run/add-openapi-docs/slim/)
- [Generate an API Reference From an OpenAPI Spec in a Starlight Site](https://getrush.ai/run/add-openapi-docs/starlight/)
- [Generate OpenAPI Docs from a tRPC Router](https://getrush.ai/run/add-openapi-docs/trpc/)

## 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/)
