# Add OpenAPI Docs to a Slim 4 App

Yes. An agent annotates your Slim 4 actions and domain objects with swagger-php attributes, generates openapi.json, checks it in CI and tests, and opens a PR.

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

## What the agent does

The agent reads the actions and the payload classes before it writes a single attribute, because in a Slim app the response shape is decided by a base class, not by the route. In an app laid out like slimphp/Slim-Skeleton, `app/routes.php` registers `GET /` (a `Hello world!` string), an `OPTIONS /{routes:.*}` catch-all for CORS pre-flight, and a `/users` group with `GET ''` on `ListUsersAction` and `GET /{id}` on `ViewUserAction`. Both extend `UserAction`, which takes a `LoggerInterface` and a `UserRepository`, and that extends `Action`, whose `respondWithData` wraps anything in an `ActionPayload` and whose `respond` writes it as pretty-printed JSON with `Content-Type: application/json`. `ActionPayload::jsonSerialize` emits `statusCode` and then either `data` or `error`; `ActionError` has a `type` drawn from nine constants (`BAD_REQUEST`, `INSUFFICIENT_PRIVILEGES`, `NOT_ALLOWED`, `NOT_IMPLEMENTED`, `RESOURCE_NOT_FOUND`, `SERVER_ERROR`, `UNAUTHENTICATED`, `VALIDATION_ERROR`, `VERIFICATION_ERROR`) and a `description`, and `HttpErrorHandler` maps a `HttpNotFoundException` to `RESOURCE_NOT_FOUND`. `User::jsonSerialize` returns `id`, `username`, `firstName` and `lastName`.

The tool is `zircote/swagger-php`. Its 7.x line requires PHP 8.2, while `composer.json` allows `php` `^7.4 || ^8.0` and `.github/workflows/tests.yml` runs a matrix of `7.4`, `8.0`, `8.1` and `8.2` with `phpcs` and `phpstan` on the `8.1` job. The agent therefore requires `zircote/swagger-php` at `^5.8`, whose floor is PHP 7.4, as a dev dependency, and writes the annotations as PHP 8 attributes (`#[OA\Get(...)]`, `#[OA\Schema(...)]`, `#[OA\Property(...)]`). PHP 7.4 reads an attribute line as a comment, so every job in the matrix still compiles and runs the suite; only the spec generation needs PHP 8, and the agent puts that step on the `8.1` analysis job. The pull request says this plainly and offers the alternative of docblock annotations with `doctrine/annotations` for a team that wants the spec built on 7.4.

The attributes go where the facts are. `src/Application/OpenApi/OpenApi.php` is a new, otherwise empty class that carries `#[OA\Info(title: 'Slim Skeleton API', version: '1.0.0')]` and the server. `ListUsersAction` gets `#[OA\Get(path: '/users', summary: 'List users')]` with a `200` response whose schema is an `ActionPayload` with `data` as an array of `User`; `ViewUserAction` gets `path: '/users/{id}'`, an integer `#[OA\PathParameter]` and a `404` response whose `error.type` is `RESOURCE_NOT_FOUND`. `User`, `ActionPayload` and `ActionError` get `#[OA\Schema]` with one `#[OA\Property]` per field that `jsonSerialize` emits, the `type` property carrying the nine constants as an `enum`. `GET /` and the `OPTIONS` catch-all are left undocumented on purpose. A `composer openapi` script runs `vendor/bin/openapi src --format json --output public/openapi.json`, so the generated file is served by the existing `php -S localhost:8080 -t public` with no new route, and the `analysis` job gains a step that regenerates it and fails on `git diff --exit-code public/openapi.json`, which keeps the committed spec in step with the code.

Tests stay in PHPUnit. `tests/Application/OpenApiTest.php` calls `\OpenApi\Generator::scan([__DIR__ . '/../../src'])` in-process, asserts the document has the `/users` and `/users/{id}` paths, that the `User` schema lists the four properties, and that the `404` response references `ActionError`; it calls `markTestSkipped` when `PHP_VERSION_ID < 80000`, because attributes are not read there. The agent runs `vendor/bin/phpunit`, `vendor/bin/phpstan` at the level 4 that `phpstan.neon.dist` sets, `vendor/bin/phpcs` under the PSR-12 ruleset in `phpcs.xml`, then `composer openapi` and `curl localhost:8080/openapi.json` in its sandbox, and validates the generated file with the `openapi` binary's own parse.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add OpenAPI docs to this Slim 4 app with swagger-php. Read composer.json, .github/workflows/tests.yml, app/routes.php, src/Application/Actions (Action, ActionPayload, ActionError and the User actions), src/Domain/User/User.php, src/Application/Handlers/HttpErrorHandler.php, phpunit.xml, phpstan.neon.dist and phpcs.xml first. Pick the swagger-php major that fits the composer php constraint, write PHP 8 attributes on the actions and on User, ActionPayload and ActionError so the generated schemas match what jsonSerialize emits, add an Info attribute, and document the users routes only. Add a composer openapi script that writes public/openapi.json, commit the generated file, and add a CI step on the analysis job that regenerates it and fails if it differs. Add a PHPUnit test that scans src in-process and asserts the paths and schemas, skipped below PHP 8. Run phpunit, phpstan, phpcs and the generator, and open a pull request with the output.",
  "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

The pull request adds `src/Application/OpenApi/OpenApi.php`, `public/openapi.json` and `tests/Application/OpenApiTest.php`, and changes `composer.json`, `src/Application/Actions/User/ListUsersAction.php`, `src/Application/Actions/User/ViewUserAction.php`, `src/Application/Actions/ActionPayload.php`, `src/Application/Actions/ActionError.php`, `src/Domain/User/User.php` and `.github/workflows/tests.yml`. Its description pastes the generated document's `paths` block, the `phpunit`, `phpstan` and `phpcs` results, and the `curl` of `/openapi.json` from the built-in server.

The `Tests` workflow runs on the pull request, so a reviewer sees the suite pass on every PHP in the matrix and the spec-drift step pass on 8.1. The run's record keeps each command and its output, including the generator's own warnings if any attribute was incomplete.

Before merging, a reviewer sets the real title, version and server URL in the `Info` attribute, decides whether to serve a Swagger UI page or leave the JSON for tooling, and whether the `OPTIONS` catch-all and `GET /` should be documented after all. The routes, the container and the repository classes are unchanged.

## Run it on every Slim service without an API spec

A team with several Slim services sends this body once per repository to `POST /o/{org}/sessions`, each with its own repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started rather than opening a second pull request. Each run reads its own actions, so a service with `POST` routes gets request-body schemas drawn from its `getFormData` usage, and one already on swagger-php gets its missing routes filled in rather than a second `Info` block.

Once the drift step is in CI, no scheduled run is needed: a route added without attributes fails the `analysis` job on its own pull request. An automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request adds or changes an action, check that its OpenAPI attributes match the response the action builds and comment with the missing property or status code" turns that failure into a review comment with the fix. The trigger adds the pull request after the prompt; only work by an owner, member or collaborator fires it.

## Why run it on Rush?

An OpenAPI document written by hand drifts from the code within weeks, and one generated without reading `ActionPayload` describes a response shape the app never sends. The agent reads the base class that wraps every response, the error handler that chooses the error type, and the entity that serialises the fields, then runs the generator and the suite on the matrix the repository already has, so the spec it commits is the one the code produces.

The generator output, the three analysis tools and the `curl` of the served file all stay with the run, and the pull request quotes them. Several Slim services can be documented at once, each in its own sandbox, with a spec-drift check that keeps each one honest after the merge.

## Frequently asked questions

### Why swagger-php 5 and not the current 7?

Because swagger-php 7 requires PHP 8.2 and the skeleton's `composer.json` still allows 7.4 and 8.0, with a CI matrix to match. The 5.x line supports PHP 7.4 and later and reads the same PHP 8 attributes, so a team that later raises the PHP floor can move to 7 with a one-line constraint change. The pull request names that constraint.

### Will the attributes break the PHP 7.4 job?

No. PHP 7.4 parses `#[...]` as a line comment, so the classes compile and the existing tests run as before. Attributes are only read on PHP 8, which is why the generator step runs on the `8.1` analysis job and the new PHPUnit test skips itself below 8.0.

### Do I get a Swagger UI page?

Not from this run. The pull request serves `openapi.json` from `public/` so any tool, including a hosted Swagger UI or Redoc, can load it, and the description shows how to add a static UI page that points at it. Keeping the UI out of the app avoids a new route and a front-end dependency the skeleton does not have.

### What stops the spec from going stale?

The CI step that regenerates `public/openapi.json` and fails on `git diff --exit-code` when the committed file differs. Anyone who adds a route without attributes, or changes a response without updating them, sees a red check on their pull request with the diff in the log.

## More Slim jobs

- [Add OpenTelemetry Tracing to a Slim 4 App](https://getrush.ai/run/add-opentelemetry/slim/)
- [Add Pagination to a Slim 4 List Endpoint](https://getrush.ai/run/add-pagination/slim/)
- [Add Prometheus Metrics to a Slim 4 App](https://getrush.ai/run/add-prometheus-metrics/slim/)

## The same job on other stacks

- [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/)
- [Add OpenAPI Docs to a Vapor API](https://getrush.ai/run/add-openapi-docs/vapor/)

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