# Add Input Validation to a Ktor API

Yes. An agent installs Ktor's RequestValidation and StatusPages plugins, checks the Article body against the column limits, adds tests and opens a PR.

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

## What the agent does

The agent reads the routes and the schema they write to. In a service shaped like the `postgres` sample in ktorio/ktor-samples, `build.gradle.kts` uses the Ktor Gradle plugin 3.6 with Kotlin 2.4, `ktor-server-content-negotiation` with `kotlinx-json`, Netty, the YAML config plugin and the PostgreSQL JDBC driver, with `ktor-server-test-host` and `kotlin-test-junit` declared for tests and a JVM toolchain of 17. `plugins/Routing.kt` serves `POST /articles`, which calls `call.receive<Article>()` and inserts, and `GET`, `PUT` and `DELETE /articles/{id}`, which parse the id with `toInt()` and map `IllegalArgumentException` to 400. `models/Article.kt` is a `@Serializable data class Article(val title: String, val body: String)` with no constraints, while `service/ArticleService.kt` creates the table with `TITLE VARCHAR(255)` and `BODY VARCHAR(1024)`. An empty title is accepted, and a body over 1024 characters reaches Postgres, fails there and comes back as a 500. There is no `src/test` directory.

It adds `ktor-server-request-validation` and `ktor-server-status-pages` to the dependencies and a `plugins/Validation.kt` that installs `RequestValidation` with a `validate<Article>` block: the title must not be blank and must fit 255 characters, the body must not be blank and must fit 1024, each failure named in a `ValidationResult.Invalid` with a message a client can show. `StatusPages` maps `RequestValidationException` to a 400 JSON body listing the reasons, `BadRequestException` from malformed JSON to a 400, and the sample's own `DbElementNotFoundException` to 404, which replaces the try and catch blocks in `Routing.kt`. The id parsing switches to `toIntOrNull()` with a 400 when it is not a number. `PostgresApplication.kt` calls the new `configureValidation()` after `configureSerialization()`.

Tests are new to this sample, so the agent creates `src/test/kotlin/com/example/ValidationTest.kt` with Ktor's `testApplication`, installing the same plugins and a routing over an `ArticleService` backed by an in-memory H2 connection in PostgreSQL mode, following the sibling `h2` sample for the test dependency, since the `CREATE TABLE IF NOT EXISTS` in the service runs on it. The cases are: a valid article returns 201 with an id, a blank title returns 400 with the title reason, a body of 1025 characters returns 400 with the body reason, a request with `{"title": 1}` returns 400 rather than 500, and `GET /articles/abc` returns 400.

The agent runs `./gradlew test` in the sample and `./gradlew build`, which is what the repository's `build-all.sh` does for every sample under the `Build All Samples` workflow on JDK 24, and pastes the test report summary in the pull request. It also starts Postgres from the sample's `docker-compose.yaml`, runs `./gradlew run` and posts a blank-title article with `curl` to show the real 400 body.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add input validation to this Ktor service and open a pull request. Read build.gradle.kts, gradle.properties, src/main/resources/application.yaml, src/main/kotlin/com/example/PostgresApplication.kt, plugins/Routing.kt, plugins/Serialization.kt, models/Article.kt, service/ArticleService.kt and the two exception classes first. Add ktor-server-request-validation and ktor-server-status-pages. Add plugins/Validation.kt installing RequestValidation with a validate<Article> block requiring a non-blank title of at most 255 characters and a non-blank body of at most 1024 characters, matching the VARCHAR widths in ArticleService, and StatusPages mapping RequestValidationException and BadRequestException to 400 with a JSON list of reasons and DbElementNotFoundException to 404. Remove the try and catch blocks in Routing.kt that this replaces and parse the id with toIntOrNull. Call configureValidation from the module. Add src/test/kotlin/com/example/ValidationTest.kt using testApplication over an ArticleService on an in-memory H2 connection in PostgreSQL mode, as the h2 sample in this repository does, covering a valid create, a blank title, an over-long body, a wrongly typed field and a non-numeric id. Run ./gradlew test and ./gradlew build, start Postgres from docker-compose.yaml and run the service, and paste the test summary and one real 400 response in the pull request. Do not change the SQL in ArticleService.",
  "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 two new dependencies in `build.gradle.kts`, a new `plugins/Validation.kt`, a shorter `plugins/Routing.kt`, one line in `PostgresApplication.kt`, and the first test file in the sample. The description shows the Gradle test summary and one 400 response body from the running service with its list of reasons.

On a repository that runs `build-all.sh` on pull requests, the checks compile and test this sample with the others, so a plugin installed twice or a test that needs a live Postgres fails there. A reviewer who wants the H2 dependency kept out of the main classpath checks that it sits under `testImplementation` only.

A reviewer also checks that the limits match the columns, that the 404 mapping did not swallow the 500 path for a failed insert, and that the error body shape is one their client already parses. Then they add the same `validate<T>` block for the next model.

## Run it on every new endpoint merged

A team that wants every Ktor service to refuse bad input at the edge sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own models and table definitions, so a service whose columns are `TEXT` gets a length-free rule set and one that already has `StatusPages` gets its mapping extended rather than replaced, and each opens its own pull request.

A `webhook_url` on the key reports `run.completed` per run with `data.session_url`, so one handler can list the pull requests for review.

## Why run it on Rush?

Validation is a change where the test matters more than the code: the rule that was meant to be a 400 returns a 500 because the plugin is installed after the route, or the StatusPages handler catches more than intended. In a Rush sandbox the agent runs Gradle, starts Postgres with Docker Compose, sends the bad requests with `curl` and keeps every command and response in the run's record, so the pull request shows the real status codes.

The first test file in a sample is also the one most likely to be put off on a laptop, because the JVM toolchain, the Gradle download and the database all take time nobody has at five in the afternoon. The sandbox has the time, and the turn parks when it is done so a follow-up can add the next model's rules.

## Frequently asked questions

### Why validate against 255 and 1024?

Because `ArticleService.kt` creates the table with `TITLE VARCHAR(255)` and `BODY VARCHAR(1024)`. Anything longer fails inside Postgres and surfaces as a 500, so matching the limits in the plugin turns that into a clear 400 before the insert.

### Does this change the JSON the service accepts?

No. `Article` keeps its two fields and the content negotiation plugin stays as it is. Only the responses for bad input change, from a 500 or a silent insert to a 400 with reasons.

### How do the tests run without Postgres?

The test builds the routing over an `ArticleService` on an in-memory H2 connection in PostgreSQL compatibility mode, under `testImplementation` only, so `./gradlew test` needs no database. The real Postgres check is done once in the sandbox and pasted in the pull request.

### Can I return the errors in a different shape?

Yes. The `StatusPages` handler is one block in `Validation.kt`, and the test asserts on it, so changing the body to your API's error envelope is a two-file edit a follow-up can make.

## More Ktor jobs

- [Add JWT Authentication to a Ktor API](https://getrush.ai/run/add-jwt-auth/ktor/)
- [Add OpenAPI Docs to a Ktor Server](https://getrush.ai/run/add-openapi-docs/ktor/)
- [Add OpenTelemetry Tracing to a Ktor Server](https://getrush.ai/run/add-opentelemetry/ktor/)

## The same job on other stacks

- [Add Input Validation to a Node.js Express App](https://getrush.ai/run/add-input-validation/nodejs/)
- [Add Input Validation to a Quarkus REST API](https://getrush.ai/run/add-input-validation/quarkus/)
- [Add Input Validation to a Sequelize and Express API](https://getrush.ai/run/add-input-validation/sequelize/)

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