# Add Input Validation to a Slim 4 API

Yes. An agent validates route arguments and bodies in your Slim 4 actions, answers 422 in the skeleton's own error shape, tests it with PHPUnit, and opens a PR.

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

## What the agent does

The agent reads where input enters before it validates any of it. In a Slim 4 app like slimphp/Slim-Skeleton, `composer.json` requires `slim/slim` `^4.12`, `slim/psr7` `^1.6`, `php-di/php-di` `^6.4` and `monolog/monolog` `^2.9` on `php ^7.4 || ^8.0`, and the `tests.yml` workflow runs `phpunit` on PHP 7.4, 8.0, 8.1 and 8.2 with `phpcs` and `phpstan` at level 4 on the 8.1 job, so any new code has to stay 7.4-compatible. `app/routes.php` registers `GET /`, `GET /users` to `ListUsersAction` and `GET /users/{id}` to `ViewUserAction`, plus an `OPTIONS` catch-all. `ViewUserAction::action` does `(int) $this->resolveArg('id')` and hands the result to `UserRepository::findUserOfId`, which throws `UserNotFoundException` for an unknown id; `Action::__invoke` turns that into `HttpNotFoundException`, and `HttpErrorHandler::respond` renders it as an `ActionPayload` carrying an `ActionError` of type `RESOURCE_NOT_FOUND`. That cast is the problem: `/users/abc` becomes user 0 and a 404, `/users/1.5` and `/users/1abc` both become user 1 and answer with Bill Gates, and `/users/-1` is a 404 that should have been a complaint about the input. `ActionError` already defines a `VALIDATION_ERROR` constant, but nothing in `src/` throws it.

The agent adds the missing path from bad input to that constant. A `HttpUnprocessableEntityException` under `src/Application/Handlers/`, extending Slim's `HttpSpecializedException` with code 422 and a message, gets its own branch in `HttpErrorHandler::respond` that sets `ActionError::VALIDATION_ERROR`, beside the existing branches for not found, method not allowed and the others. `Action` gains two protected helpers: `resolveIntArg(string $name, int $min = 1)`, which runs `resolveArg` through `filter_var` with `FILTER_VALIDATE_INT` and a range, so `abc`, `1.5`, `1abc`, `-1` and a value past `PHP_INT_MAX` all throw the 422 with a sentence naming the argument; and `validateFormData(array $rules)`, which reads `getFormData()`, checks required keys, types and lengths from a small rule array, and throws the same exception with a description listing every failing field. The existing `getFormData()` already returns what `addBodyParsingMiddleware` parsed in `public/index.php`, so JSON and form bodies both arrive as arrays.

`ViewUserAction` switches to `resolveIntArg('id')`, and the route stays `/users/{id}` rather than `/users/{id:[0-9]+}`: a regex constraint would make `/users/abc` a 404 from the router before any action runs, and the prompt asks for a validation error that says what was wrong. The skeleton has no `POST` route, so the body validator is exercised where the reader's prompt names a writing action; here the agent adds `validateFormData` to the abstract `Action` with a unit test over a stub action, so the next `CreateUserAction` has it ready. The description shows what a client sees for each case: 404 with `RESOURCE_NOT_FOUND` for an unknown but valid id, 422 with `VALIDATION_ERROR` and a description for a malformed one.

Tests follow `ViewUserActionTest`: each case builds the app with `getAppInstance()`, adds an `ErrorMiddleware` with `HttpErrorHandler` the way `testActionThrowsUserNotFoundException` does, sends `createRequest('GET', '/users/abc')` and the other malformed ids, and compares the body to a `json_encode` of the expected `ActionPayload(422, null, new ActionError(ActionError::VALIDATION_ERROR, …))`. A repository prophecy with `findUserOfId` set to `shouldNotBeCalled()` proves the lookup never runs on bad input. The agent runs `composer install`, `vendor/bin/phpunit`, `vendor/bin/phpstan` and `vendor/bin/phpcs` in its sandbox and reads the output; `phpcs.xml` and `phpstan.neon.dist` are respected rather than changed.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add input validation to this Slim 4 API. Read composer.json, public/index.php, app/routes.php, app/dependencies.php, src/Application/Actions/Action.php, ActionError.php, ActionPayload.php, src/Application/Actions/User/ViewUserAction.php, src/Application/Handlers/HttpErrorHandler.php, tests/TestCase.php, tests/Application/Actions/User/ViewUserActionTest.php and the CI workflow first. Add a 422 HttpUnprocessableEntityException and map it in HttpErrorHandler to the existing ActionError::VALIDATION_ERROR type. Add resolveIntArg and validateFormData helpers on the abstract Action, using filter_var with FILTER_VALIDATE_INT and a rule array, and use resolveIntArg in ViewUserAction so /users/abc, /users/1.5, /users/1abc, /users/-1 and an overflow answer 422 with a message naming the argument instead of being cast to an id. Keep the route placeholder unconstrained and explain why in the PR. Keep everything PHP 7.4 compatible. Add PHPUnit tests in the style of ViewUserActionTest for each malformed id, assert the repository is not called, and add a unit test for validateFormData over a stub action. Run phpunit, phpstan and phpcs and include the output. Open a pull request.",
  "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 `src/Application/Handlers/HttpUnprocessableEntityException.php` and `tests/Application/Actions/ValidationTest.php`, and changes `src/Application/Actions/Action.php`, `src/Application/Actions/User/ViewUserAction.php`, `src/Application/Handlers/HttpErrorHandler.php` and `tests/Application/Actions/User/ViewUserActionTest.php`. `app/routes.php`, `ActionError.php`, `composer.json` and the repository classes are unchanged.

The description shows the before and after for each malformed id, explains why the placeholder keeps no regex, and quotes the `phpunit`, `phpstan` and `phpcs` results. The commands and full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer checks that 422 is the status their clients expect for a bad argument, some teams prefer 400, and that the error descriptions do not echo more of the input than they should. A follow-up message to the same session can switch the status code, add a `details` array to `ActionError` listing fields, or apply `validateFormData` to an existing `POST` action.

## Run it on every PHP API that casts its route arguments instead of checking them

A team with several Slim services starts one run per repository with one `POST /o/{org}/sessions` each, the repository in `resources` and this prompt as `input`. Each run reads its own actions, so a service with `POST` routes gets `validateFormData` applied to each of them with rules drawn from what the action reads, and one with a different error handler gets the mapping added there.

Send a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` reports when each run the key starts finishes, with the run's final answer in `result` and `session_url` for the pull request link.

## Why run it on Rush?

Validation bugs hide in casts: `(int) '1.5'` is 1, `(int) 'abc'` is 0, and both produce a plausible response rather than an error. The agent reads the exact path from route argument to repository call, adds the one exception type the error handler lacks, and proves each bad input with PHPUnit in a sandbox of its own, with the output kept.

The pull request carries the helpers, the mapping and the tests, so review is a diff with five new assertions rather than a round of `curl` against a dev server. Several services can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why not constrain the route with {id:[0-9]+}?

Slim then never invokes the route for `/users/abc` and the router answers 404, which hides the real problem from the client. Validating in the action answers 422 with a message naming the argument. If you prefer the 404, say so and the agent adds the constraint instead.

### Why 422 and not 400?

The skeleton already maps Slim's `HttpBadRequestException` to `BAD_REQUEST` for a missing argument, so a separate code keeps malformed input distinct from a missing one. The exception's code is one constant; a follow-up can make it 400.

### Does this change the JSON error shape?

No. A validation failure is an `ActionPayload` with `statusCode` 422 and an `error` holding `type` and `description`, exactly the shape every other error already uses, so clients need no new parsing.

### Does it need a validation library?

No. `filter_var` and a small rule array cover integers, required keys, types and lengths, and the code stays on PHP 7.4 as the CI matrix requires. If you use `respect/validation` or similar, name it and the agent wires it behind the same exception.

### Which PHP versions does it test on?

The agent runs the suite on the PHP in its sandbox and writes code without enums, readonly properties or other features newer than 7.4, because `tests.yml` runs the suite on 7.4 through 8.2. The workflow then runs on the pull request as it does for every push.

## More Slim jobs

- [Add JWT Authentication to a Slim 4 API](https://getrush.ai/run/add-jwt-authentication/slim/)
- [Add OpenAPI Docs to a Slim 4 App](https://getrush.ai/run/add-openapi-docs/slim/)
- [Add OpenTelemetry Tracing to a Slim 4 App](https://getrush.ai/run/add-opentelemetry/slim/)

## The same job on other stacks

- [Add Input Validation to a Socket.IO Chat](https://getrush.ai/run/add-input-validation/socket-io/)
- [Add Request Validation to a Vapor API](https://getrush.ai/run/add-input-validation/vapor/)
- [Add Input Validation to an Actix Web App from a Linear Issue](https://getrush.ai/run/add-input-validation/actix/)

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