# Add Input Validation to an Axum API

Yes. An agent adds request validation to an Axum API that reports every bad field at once as a 422 in the app's own error shape, with unit tests, and opens a PR.

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

## What the agent does

The agent reads how requests already fail before it adds a check. In an API shaped like launchbadge/realworld-axum-sqlx, `Cargo.toml` pins `axum` 0.3.4, `sqlx` 0.5 on Postgres, `argon2` 0.3.1, `thiserror` and `serde`. `src/http/users.rs` deserializes `NewUser { username, email, password }`, `LoginUser` and an `UpdateUser` of `Option` fields with `#[serde(default)]`; `create_user` hashes the password with Argon2 and runs the insert, and the only validation is the database's: `on_constraint("user_username_key")` and `on_constraint("user_email_key")` map a unique violation to `Error::unprocessable_entity`. `migrations/2_user.sql` declares `username` and `email` as `not null` text with a case-insensitive collation, `bio` as `not null default ''`, and `image` as nullable. An empty username reaches Postgres and is stored; an empty password is hashed and stored too. `src/http/error.rs` already has the right error for the job: `Error::UnprocessableEntity { errors: HashMap<Cow, Vec<Cow>> }` renders as `422` with a JSON `errors` map, the shape the Realworld spec asks for, and `Error::unprocessable_entity` collects several messages under one key.

The agent adds `src/http/validate.rs` with a small `Validator` that accumulates `(field, message)` pairs and turns into `Error::unprocessable_entity` when any were recorded, so a request with a blank username and a short password gets both messages in one response rather than one per round trip. The rules are plain functions: `not_blank`, `max_len`, `min_len`, `looks_like_email`. Limits live as named constants at the top of the module so a reviewer changes one line, and the pull request lists each with its reason. No new crate is added; the `validator` crate would pull a derive macro and its own error type into a codebase whose comments explain why it keeps its one `Error` enum.

The handlers call it before any work. `create_user` validates `username`, `email` and `password` and returns before hashing, which matters because Argon2 is built to be slow and a blank password was paying that cost. `login_user` checks `email` and `password` are present so a missing field gives `422` instead of the `email does not exist` message. `update_user` validates each `Option` only when it is `Some`, so `{"user": {}}` stays a no-op, and an explicit empty string for `email` or `username` is refused. In `src/http/articles/mod.rs`, `create_article` requires `title`, `description` and `body`, because `slugify` of an empty title produces an empty slug that the unique index on `article` would reject with a confusing message, and `tag_list` entries are trimmed and blank ones dropped before the existing sort.

Tests go in a `#[cfg(test)] mod tests` inside `validate.rs`, so they run with `cargo test` and without Postgres, covering each rule and the accumulation of several errors into one map. The `sqlx::query!` macros check queries against a live database at compile time, so the agent starts Postgres in the sandbox, sets `DATABASE_URL` and `HMAC_KEY` as `.env.sample` describes, runs `sqlx db setup` as `.github/workflows/rust.yml` does, then `cargo build --verbose`, `cargo test --verbose`, and the Realworld Postman collection the workflow checks out and runs through `./run-api-tests.sh` against `http://localhost:8080/api`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add input validation to this Axum API and open a pull request. Read Cargo.toml, src/http/mod.rs, src/http/error.rs, src/http/users.rs, src/http/profiles.rs, src/http/articles/mod.rs, migrations/2_user.sql, .env.sample and .github/workflows/rust.yml first. Add src/http/validate.rs with a Validator that accumulates field errors and converts into the existing Error::unprocessable_entity, with not_blank, min_len, max_len and looks_like_email rules and named constants for every limit. Validate NewUser before the password is hashed, LoginUser before the lookup, each present field of UpdateUser, and title, description and body of CreateArticle, trimming tag_list entries and dropping blank ones. Do not add a validation crate and do not change the 422 response shape. Add unit tests for the rules and for several errors in one response in a cfg(test) module. Start Postgres, set DATABASE_URL and HMAC_KEY, run sqlx db setup, cargo build, cargo test and the Realworld Postman collection the workflow runs, and paste the cargo test output and one 422 response body 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 that adds `src/http/validate.rs`, registers it in `src/http/mod.rs`, and edits the handlers in `users.rs` and `articles/mod.rs` without touching `error.rs`, `extractor.rs` or any migration. The description shows the `cargo test` output with the new unit tests, and one `curl` of `POST /api/users` with an empty body whose `422` response lists `username`, `email` and `password` together under `errors`.

On a repository with this `Rust` workflow the pull request builds against the Postgres service, runs `cargo test`, then starts the server and runs the Realworld Postman collection. The collection registers and logs in with valid data and reads `errors` on failures, so it passes with the same shape it passed with before.

A reviewer checks the limits in the constants against what the clients send, that `update_user` with an absent field still leaves it unchanged, and that `login_user` no longer reveals through its message whether an email is registered. Then they merge.

## Run it on every new public endpoint

A team with several Axum services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own error type and request structs, so a service that already uses the `validator` crate gets rules written with its derives instead of a new module, and each opens its own pull request with tests that run in that project's `cargo test`.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from, so a handler on your server can post the link where that service's owners review.

## Why run it on Rush?

Validation is easy to write and easy to get subtly wrong: a check after the password hash wastes the slowest call in the handler, and an `Option` field validated as if it were required turns every settings update into a 422. In a Rush sandbox the agent compiles against a real Postgres, because `sqlx::query!` demands one, runs the unit tests and the Postman collection, and keeps every command and its output in the run's record, so the pull request shows a `422` body rather than promising one.

This repository's CI needs a database service, `sqlx-cli`, a checked-out fork of the Realworld collection and Newman, which is a long afternoon to reproduce on a laptop. Each run on Rush sets that up in its own sandbox, and the same request body works on every Axum service a team owns.

## Frequently asked questions

### Why not the validator crate?

It would work, and the agent uses it if the prompt asks. The default is a small module with no new dependency because the app already has a `422` error type with a map of messages per field, and a derive macro would add a second error type to convert from. The rules fit in one file with tests.

### Does it change what the database enforces?

No. The unique indexes and `not null` constraints in `migrations/2_user.sql` stay, and the `on_constraint` mappings keep handling a taken username or email. Validation runs first so blank or oversized values never reach them.

### Will the Realworld Postman collection still pass?

Yes. The collection sends valid registrations and expects `422` with an `errors` map on failures, which is the shape `Error::UnprocessableEntity` already renders. The run executes the collection the same way `rust.yml` does and pastes the summary.

### What about the email check?

`looks_like_email` requires one `@` with something on both sides and no whitespace. A full RFC 5322 parser rejects addresses that mail servers accept, so the pull request keeps the rule loose and says why.

## More Axum jobs

- [Add OpenAPI Docs to an Axum API from a Linear Issue](https://getrush.ai/run/add-openapi-docs/axum/)
- [Add Prometheus Metrics to an Axum API](https://getrush.ai/run/add-prometheus-metrics/axum/)
- [Add Rate Limiting to an Axum API](https://getrush.ai/run/add-rate-limiting/axum/)

## The same job on other stacks

- [Validate Request Bodies in a Cloudflare Worker](https://getrush.ai/run/add-input-validation/cloudflare-workers/)
- [Add Input Validation to a Fiber API](https://getrush.ai/run/add-input-validation/fiber/)
- [Add Input Validation to Firebase Cloud Functions](https://getrush.ai/run/add-input-validation/firebase-functions/)

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