# Add Request Validation to a Vapor API

Yes. An agent adds Vapor's Validatable to your DTOs so a bad request body answers 400 with a clear message instead of a database error, with tests, and opens a PR.

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

## What the agent does

The agent reads how a request becomes a row. In a project generated from vapor/template with Fluent, `Package.swift` on Swift tools 6.3 depends on Vapor from 4.121 and Fluent from 4.13 with the `VaporTesting` product for tests, and turns on the `ExistentialAny` and `MemberImportVisibility` upcoming features. `Sources/App/Controllers/TodoController.swift` registers `GET`, `POST` and `DELETE` under `todos`, and `create` does `try req.content.decode(TodoDTO.self).toModel()` and saves it. `Sources/App/DTOs/TodoDTO.swift` declares `title` as `String?`, and `toModel()` only assigns the title when it is present, while `Sources/App/Migrations/CreateTodo.swift` makes the `title` column `.required`. So a body with no title, or an empty one, is decoded without complaint and fails later inside Fluent as a server error, with no message a client can act on.

It adds validation at the edge, in Vapor's own way. `TodoDTO` gains an `extension TodoDTO: Validatable` whose `validations(_:)` adds `title` as a `String` that is not empty and not longer than the column should hold, with a `required: true` so a missing key is a validation failure too. In `TodoController.create`, `try TodoDTO.validate(content: req)` runs before `decode`, so a bad body stops there and Vapor answers `400 Bad Request` with the failing key and the reason in the error body, in the format the default `ErrorMiddleware` already uses for `Abort`. Because `validate(content:)` reads the request body independently, the decode that follows sees the same bytes.

A second pass closes the gap that let the bug through. `toModel()` currently leaves `title` unset when the DTO has none; with validation in front it cannot happen, but the agent makes the intent explicit by keeping `title` optional in the DTO for responses, where `toDTO()` reads `self.$title.value`, and documenting that the create path validates first. `DELETE todos/:todoID` already answers `404` through `Abort(.notFound)` when `Todo.find` returns nothing; the agent adds a validation on the path parameter so a non-UUID id answers `400` rather than falling through to `404`, and leaves `GET todos` alone.

Tests go in `Tests/AppTests/AppTests.swift`, which already uses Swift Testing with a `withApp` helper that configures the app, runs `autoMigrate`, the test, and `autoRevert`. New cases send `POST todos` with an empty title, a missing title and a title past the limit, assert `.badRequest` and that `Todo.query(on: app.db).all()` is still empty, and one sends a valid body to show the happy path still answers `.ok` with the DTO. The agent runs `swift build` and `swift test` as `TEMPLATE_README.md` describes and as the template's own workflow does for the Fluent variants, and sends the three bad bodies to the running server with `curl` to show the exact JSON a client sees.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add request validation to this Vapor API and open a pull request. Read Package.swift, Sources/App/configure.swift, Sources/App/routes.swift, Sources/App/Controllers/TodoController.swift, Sources/App/DTOs/TodoDTO.swift, Sources/App/Models/Todo.swift, Sources/App/Migrations/CreateTodo.swift and Tests/AppTests/AppTests.swift first. Make TodoDTO conform to Validatable with a required title that is a non-empty String with a sensible maximum length matching the column. In TodoController.create call TodoDTO.validate(content:) before decoding so a bad body answers 400 through the default ErrorMiddleware with the failing key and reason. Validate the todoID path parameter on delete so a non-UUID answers 400. Do not change the model, the migration or the GET route. Add tests to Tests/AppTests/AppTests.swift in the existing Swift Testing style using withApp: an empty title, a missing title and an over-long title each answer badRequest and leave the todos table empty, and a valid body still answers ok. Run swift build and swift test, start the server and send the three bad bodies with curl, and paste the test output and the curl responses in the 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 with the `Validatable` extension in `Sources/App/DTOs/TodoDTO.swift`, two lines in `Sources/App/Controllers/TodoController.swift` for the body and path validations, and four new `@Test` functions in `Tests/AppTests/AppTests.swift`. The description pastes the `swift test` summary from the sandbox and the three `curl` exchanges, each showing the `400` status and the JSON error body naming `title` and the rule that failed.

If the repository runs the template's `test` workflow, the `swift test` job in the `swift:6.3-noble` container runs the new cases on the pull request for each Fluent driver. The agent pushes one commit for the validation and one for the tests, so the behaviour change can be read apart from its proof.

A reviewer checks that the limit on `title` matches what the `.string` column holds for their database, that a missing key and an empty string both answer `400` rather than one of them slipping through to Fluent, that the happy path still returns the DTO with its id, and that the `GET` route is unchanged. Then they merge and point their client's error handling at the `reason` field.

## Run it on every new DTO

Each time a route gains a request body, start one run with `POST /o/{org}/sessions`, this prompt narrowed to the new DTO and the repository in `resources`. The agent reads the DTO, the controller and the migration that holds the column constraints, writes the `Validatable` extension and the tests, and opens a pull request for that type alone.

A team tracking the work in Linear adds an automation to the Project with this prompt and a `linear` trigger on `linear.issue.labeled`; an issue such as "POST todos answers 500 on an empty title" labelled `agent` starts a run with the issue appended after the prompt, and the run reads which route to cover from it. The automation starts at most `max_runs_per_hour` runs in an hour.

## Why run it on Rush?

The bug here is invisible until a client sends the wrong thing: the code compiles, the tests pass, and an empty title becomes a database error at runtime. In a Rush sandbox the agent builds the Swift package, runs the suite against a real database through `autoMigrate`, starts the server and sends the bad bodies with `curl`, so the pull request shows the exact status and JSON a client receives, with every command kept in the transcript.

A Swift toolchain, a database and a long first build are not needed on the reader's laptop. The change is small, its tests run in the repository's own workflow, and the same request works for any Vapor app whose controllers decode a `Content` type straight into a model.

## Frequently asked questions

### Why validate before decoding?

`req.content.decode` only checks that the JSON matches the Swift types, and `title` is `String?`, so an empty or missing title decodes fine. `TodoDTO.validate(content: req)` runs the declared rules on the raw body first and throws a `ValidationsError` that the default `ErrorMiddleware` turns into `400` with the key and reason, before any database work.

### Does the error body change for existing clients?

Only for requests that used to fail with a server error. Valid requests get the same `TodoDTO` response as before, and `ErrorMiddleware` already formats `Abort` errors as `{ error: true, reason: ... }`, so the validation failures use a shape clients can already parse.

### Why keep title optional in the DTO?

`TodoDTO` is used for responses as well as requests, and `toDTO()` reads `self.$title.value`, which is optional before a model is loaded. Making the property non-optional would change the response type and `toModel()`; the `required: true` validation gives the request side the strictness it needs without that.

### Does this work with the MySQL and Postgres variants of the template?

Yes. The validation runs before Fluent and does not depend on the driver, and the tests go through `withApp`, which migrates and reverts on whatever database `configure.swift` points at. The template's own workflow runs the suite for each driver, so the pull request is checked against all of them if you use it.

## More Vapor jobs

- [Add JWT Authentication to a Vapor App from a Linear Issue](https://getrush.ai/run/add-jwt-auth/vapor/)
- [Add OpenAPI Docs to a Vapor API](https://getrush.ai/run/add-openapi-docs/vapor/)
- [Add Prometheus Metrics to a Vapor App](https://getrush.ai/run/add-prometheus-metrics/vapor/)

## The same job on other stacks

- [Add Input Validation to an Actix Web App from a Linear Issue](https://getrush.ai/run/add-input-validation/actix/)
- [Add Input Validation to an aiohttp App](https://getrush.ai/run/add-input-validation/aiohttp/)
- [Add Request Validation to an API Gateway in AWS CDK](https://getrush.ai/run/add-input-validation/aws-cdk/)

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