ValidatedJson custom extractor
Learn how to build a ValidatedJson extractor that wraps axum Json, runs validate during extraction, and returns the 422 field-error response before the handler runs
A custom extractor is a type you write that knows how to pull its own value out of a request. ValidatedJson<T> is a small wrapper around Axum's Json<T> extractor. It reads the JSON body, builds the struct, runs validate() on it, and either hands the handler a struct that is already known to be valid, or answers with the 422 field-error response before the handler ever runs. Handlers that take ValidatedJson<T> never see invalid data, because invalid data never reaches them.
Where This Fits
Calling validate in handlers put one validate() call at the top of a handler, with an early return for bad data. That pattern works, but every handler that takes input has to repeat it. The check, the early return, and the import of the helper appear again in each handler, and a handler that forgets the check accepts bad data silently. This page removes the repetition by moving the check into the extractor, so the handler signature itself guarantees the data is valid.
Think of the extractor as a gate at the door of the handler. The handler version of validation is a clerk inside the room who checks each form as it arrives. The extractor version moves the clerk to the door: bad forms are handed back outside, and only good forms ever enter the room. The handler inside the room can then trust every form it is given.
The Smallest Working Version
The smallest version wraps Json, validates, and serves one route. It needs four files: the error module with the helper, the extractor module, the library with the route, and the entry point.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use std::collections::HashMap;
use thiserror::Error;
use validator::ValidationErrors;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match &self {
AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
AppError::ValidationError(message) => {
(StatusCode::UNPROCESSABLE_ENTITY, message.clone())
}
AppError::InternalError => (
StatusCode::INTERNAL_SERVER_ERROR,
"something went wrong".to_string(),
),
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
};
let body = json!({ "error": message });
(status, Json(body)).into_response()
}
}
pub fn validation_failed(errors: &ValidationErrors) -> Response {
let mut fields: HashMap<String, Vec<String>> = HashMap::new();
for (field, kind) in errors.field_errors() {
let messages: Vec<String> = kind
.iter()
.map(|error| {
error
.message
.clone()
.map(|message| message.to_string())
.unwrap_or_else(|| error.code.to_string())
})
.collect();
fields.insert(field.to_string(), messages);
}
let body = json!({
"error": "validation failed",
"fields": fields,
});
(StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response()
}
The extractor itself lives in its own module.
use axum::{
Json,
extract::{FromRequest, Request},
response::{IntoResponse, Response},
};
use serde::Deserialize;
use validator::Validate;
use crate::errors::validation_failed;
pub struct ValidatedJson<T>(pub T);
impl<S, T> FromRequest<S> for ValidatedJson<T>
where
S: Send + Sync,
T: for<'de> Deserialize<'de> + Validate,
{
type Rejection = Response;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let Json(value) = Json::<T>::from_request(req, state)
.await
.map_err(|rejection| rejection.into_response())?;
match value.validate() {
Ok(()) => Ok(ValidatedJson(value)),
Err(errors) => Err(validation_failed(&errors)),
}
}
}
The library wires the extractor into a handler that no longer validates anything itself.
use axum::{Json, Router, routing::post};
use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::extractors::ValidatedJson;
pub mod errors;
pub mod extractors;
#[derive(Debug, Deserialize, Serialize, Validate)]
pub struct Signup {
#[validate(email(message = "enter a valid email address"))]
pub email: String,
#[validate(length(min = 3, max = 30, message = "name must be between 3 and 30 characters"))]
pub name: String,
#[validate(range(min = 18, max = 120, message = "age must be between 18 and 120"))]
pub age: u32,
}
pub async fn create_signup(ValidatedJson(input): ValidatedJson<Signup>) -> Json<Signup> {
Json(input)
}
pub fn app() -> Router {
Router::new().route("/signup", post(create_signup))
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
validator = { version = "0.21", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2.0"
Start the server with cargo run and send the same bad signup as before.
curl -X POST http://127.0.0.1:3000/signup -H "content-type: application/json" -d '{"email":"not-an-email","name":"Al","age":12}'
The response is the same 422 field-error body the handler version produced.
{"error":"validation failed","fields":{"age":["age must be between 18 and 120"],"email":["enter a valid email address"],"name":["name must be between 3 and 30 characters"]}}
A good signup answers 200 with the data echoed back. The response is identical to the handler version, but the handler no longer contains a single line of validation code. That is the whole point: the same behaviour, with the check moved out of every handler and into one place.
Working Setup:
If the bad request returns 422 with the fields map and the good request returns 200, the extractor is validating during extraction. The handler runs only for valid data, which is why its signature has no Result and no early return.
What an Extractor Is
An extractor is a type that Axum knows how to build from a request, so it can appear as a handler argument. Json<T> is an extractor: Axum reads the body, deserializes it into T, and hands the result to the handler. Path and Query are extractors too, each reading a different part of the request. A handler argument is an extractor, and the list of arguments is the list of things Axum must pull out of the request before the handler runs.
A custom extractor is one you define yourself by implementing a trait. The trait is the contract: it says which method Axum calls, what that method receives, and what it must return. Two traits exist, and the choice between them depends on whether the extractor reads the body. FromRequestParts is for extractors that only need the head of the request, such as headers. FromRequest is for extractors that read the body, such as JSON. ValidatedJson reads the body, so it implements FromRequest.
The FromRequest Trait
The trait definition, taken from the Axum 0.8 docs, is short. It has one associated type and one method.
pub trait FromRequest<S, M = ViaRequest>: Sized {
type Rejection: IntoResponse;
fn from_request(
req: Request,
state: &S,
) -> impl Future<Output = Result<Self, Self::Rejection>> + Send;
}
The S is the type of the application state, the shared data the router was built with. The extractor receives a reference to that state, even when it does not use it. The Request is the whole HTTP request, body included, passed by value because the extractor is allowed to consume the body. The return type is a future that resolves to either the extractor value or a rejection. A rejection is the error type the extractor returns when it cannot build its value, and it must implement IntoResponse, because Axum turns a rejection into the HTTP response the client receives.
The method is written as an async fn directly in the trait, using Rust's native async functions in traits. Older Axum versions needed an #[async_trait] attribute on the implementation, because the language did not support async methods in traits yet. Axum 0.8 does not need it, and adding it now is a compile error. The implementation below writes plain async fn from_request, with no attribute above the impl block.
The generic parameter M with its default ViaRequest is part of the trait's machinery for choosing how the implementation is reached. You do not write it in the impl block. Writing impl<S, T> FromRequest<S> for ValidatedJson<T> is enough, and the default fills in the rest.
No async_trait in Axum 0.8:
Axum 0.8 uses native async fn in traits for FromRequest. Do not add #[async_trait] to the implementation. Code copied from older Axum versions that carries that attribute will not compile against 0.8.
The Implementation, Piece by Piece
The implementation has five pieces, and each one maps to one line of the trait contract. They are worth reading in order, because the order is the order the work happens at runtime.
The first piece is the wrapper type itself.
pub struct ValidatedJson<T>(pub T);
This is a tuple struct with one public field, which is the Rust idiom for a wrapper. It holds a T inside and adds behaviour around it. The pub on the field lets the handler unwrap the value with ValidatedJson(input) pattern matching or with .0. The struct is generic over T, so the same wrapper works for a signup struct, a login struct, or any other validated type. The type parameter is what makes one extractor serve every route.
The second piece is the impl header with its bounds.
impl<S, T> FromRequest<S> for ValidatedJson<T>
where
S: Send + Sync,
T: for<'de> Deserialize<'de> + Validate,
The S: Send + Sync bound says the state type must be safe to share between threads. Axum requires it because handlers run on a multi-threaded runtime, and the state reference is passed into the extractor on whatever thread handles the request. The T bounds say the inner type must be deserializable from JSON and must implement Validate. Both bounds are needed: Deserialize is what the inner Json extractor requires, and Validate is what the validate() call requires. A type that fails either bound cannot be used with ValidatedJson, and the compiler reports the missing bound at the handler that tries.
The third piece is the rejection type.
type Rejection = Response;
Choosing Response as the rejection type means the extractor builds the error response itself, completely, before Axum ever sees it. The alternative would be a custom rejection type with its own IntoResponse implementation, which adds a type and an impl block for no benefit here. The responses the extractor needs to produce are already built by two helpers: validation_failed for rule failures, and the Json extractor's own rejection for body failures. Both are responses already, so Response is the natural rejection type.
The fourth piece is the inner extraction.
let Json(value) = Json::<T>::from_request(req, state)
.await
.map_err(|rejection| rejection.into_response())?;
This line delegates the hard part to the extractor being wrapped. Json::<T>::from_request reads the body and deserializes it, returning a Result<Json<T>, JsonRejection>. The ? operator returns early from the extractor when that result is an error, and the map_err call first turns the JsonRejection into a Response with into_response(), so the error type matches the declared rejection. The pattern let Json(value) = ... unwraps the Json wrapper and binds the inner struct to value. From this line on, the code works with an ordinary struct value, not with a request.
The fifth piece is the validation step.
match value.validate() {
Ok(()) => Ok(ValidatedJson(value)),
Err(errors) => Err(validation_failed(&errors)),
}
When validation passes, the value is wrapped in ValidatedJson and returned, and Axum passes it to the handler. When validation fails, the helper builds the 422 field-error body and the extractor returns it as the rejection. Axum turns that rejection into the response, and the handler never runs. The match is the whole decision. There is no third case.
The Handler After the Move
Compare the handler before and after. The handler version carried the check.
pub async fn create_signup(
Json(input): Json<Signup>,
) -> Result<Json<Signup>, axum::response::Response> {
if let Err(errors) = input.validate() {
return Err(validation_failed(&errors));
}
Ok(Json(input))
}
The extractor version carries no check at all.
pub async fn create_signup(ValidatedJson(input): ValidatedJson<Signup>) -> Json<Signup> {
Json(input)
}
The return type changed from Result<Json<Signup>, Response> to plain Json<Signup>, because the handler can no longer fail on validation. The input is valid by construction: the only way the handler receives a value is through the extractor, and the extractor only returns values that passed. A handler that cannot fail on its input does not need a Result for that failure. Other failures, such as a database error, would still need one, but validation is no longer among them.
The pattern match ValidatedJson(input) unwraps the wrapper and binds the inner struct. The .0 field access would do the same job, but pattern matching in the argument list is the usual style, and it matches how Json(input) is unwrapped. A reader who knows the Json extractor reads this handler without learning a new shape.
One Extractor, Many Structs
Because the extractor is generic over T, the same code validates any struct that derives Validate. A second struct needs no new extractor code, no new module, and no new helper. It only needs the derive and the rules.
#[derive(Debug, Deserialize, Serialize, Validate)]
pub struct Login {
#[validate(email(message = "enter a valid email address"))]
pub email: String,
#[validate(length(min = 8, message = "password must be at least 8 characters"))]
pub password: String,
}
pub async fn login(ValidatedJson(input): ValidatedJson<Login>) -> Json<Login> {
Json(input)
}
pub fn app() -> Router {
Router::new()
.route("/signup", post(create_signup))
.route("/login", post(login))
}
The login route reuses the extractor with Login in place of Signup. A bad login returns the same 422 field-error shape, with email and password as the field names. The extractor does not know or care which struct it wraps. It only knows the bounds: the type must deserialize, and it must validate. That reuse is the payoff for writing the extractor once. Ten routes with validated input share one implementation, and a fix to the error shape is made in one place.
What Happens with Malformed JSON
The extractor delegates body reading to Json, so a body that is not valid JSON is rejected by Json before validation ever runs. The rejection passes through unchanged, because the map_err call turns it into a response without touching its content. Sending a body where a field has the wrong type shows what that looks like.
curl -X POST http://127.0.0.1:3000/signup -H "content-type: application/json" -d '{"email": 42}'
The answer has status 422 and a plain text body from the Json extractor.
Failed to deserialize the JSON body into the target type: email: invalid type: integer `42`, expected a string at line 1 column 12
This body is different from the field-error body, and the difference is honest: the request never became a struct, so there are no fields to report. The field-error body only exists once a struct exists and its rules fail. A client sees two kinds of 422 from the same route. One says the JSON did not match the shape, in plain text. The other says the values broke the rules, in the fields map. Both were produced by running this code against axum 0.8.9.
The Extractor Must Be the Last Argument
An extractor that reads the body must be the last handler argument, because the body can only be consumed once. ValidatedJson reads the body through Json, so the same rule applies to it. A handler that puts another body extractor after it does not compile, because Axum cannot run two body extractors on one request. Extractors that only read the head of the request, such as headers, can come before it without a problem.
// Wrong - two body extractors cannot both run
pub async fn create_signup(
ValidatedJson(input): ValidatedJson<Signup>,
Json(other): Json<Signup>,
) -> Json<Signup> {
Json(input)
}
The rule is the same one the Json extractor itself follows, and wrapping it does not change it. When a handler needs both a header and a validated body, the header extractor goes first and ValidatedJson goes last. When a handler needs only the body, ValidatedJson is the only argument.
Body Extractors Go Last:
ValidatedJson consumes the request body, so it must be the last argument of the handler. Putting another extractor after it that also reads the body fails to compile. Head-only extractors, such as ones that read headers, can safely come before it.
The State Parameter
The from_request method receives state: &S, a reference to the application state, and this implementation ignores it. The parameter is still there, because the trait requires it. The underscore in the name is only a convention for an unused variable, and the code here names it state and simply never uses it.
An extractor that needs the state, such as one that checks a value against a database handle stored in the state, would use this parameter. ValidatedJson does not need it, because validation only looks at the struct itself. The generic S still appears in the impl header, because the trait is generic over the state type, and the S: Send + Sync bound is required whether the state is used or not. A router built with no state still works, because Axum uses the unit type () as the state in that case, and () satisfies the bound.
The Request Flow, End to End
The flow of a request through the extractor version has one fewer step inside the handler and one more step before it.
Client sends POST /signup with JSON
|
v
ValidatedJson::from_request runs
|
v
Json reads the body and builds Signup
|
v
validate() runs every rule on the struct
|
v
Fails -> 422 field-error body, handler never runs
|
v
Passes -> handler receives ValidatedJson, uses the data
The handler is the last step, and it only runs on the passing branch. The failing branch ends inside the extractor. That is the guarantee the handler signature makes: by the time the handler body executes, the data has already passed every rule.
Testing It
These tests send requests through the router with oneshot. They check the three outcomes the extractor can produce: valid data, invalid data, and a body that does not deserialize. The tower crate is a dev-dependency, because oneshot comes from tower::ServiceExt.
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn post_signup(body: &str) -> axum::response::Response {
app()
.oneshot(
Request::builder()
.method("POST")
.uri("/signup")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn invalid_signup_returns_422_field_errors() {
let response =
post_signup(r#"{"email":"not-an-email","name":"Al","age":12}"#).await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["error"], "validation failed");
assert_eq!(body["fields"]["email"][0], "enter a valid email address");
assert_eq!(
body["fields"]["name"][0],
"name must be between 3 and 30 characters"
);
assert_eq!(body["fields"]["age"][0], "age must be between 18 and 120");
}
#[tokio::test]
async fn valid_signup_returns_200() {
let response =
post_signup(r#"{"email":"ada@example.com","name":"Ada","age":30}"#).await;
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["email"], "ada@example.com");
}
#[tokio::test]
async fn malformed_json_returns_422_without_fields() {
let response = post_signup(r#"{"email": 42}"#).await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let text = String::from_utf8_lossy(&bytes).to_string();
assert!(text.contains("Failed to deserialize"));
}
#[tokio::test]
async fn login_route_reuses_the_extractor() {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/login")
.header("content-type", "application/json")
.body(Body::from(
r#"{"email":"not-an-email","password":"short"}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["error"], "validation failed");
assert_eq!(body["fields"]["email"][0], "enter a valid email address");
}
The first test pins down the contract: the status, the error string, and each field's message. The third test pins down the passthrough: a body that fails to deserialize returns 422 with the Json extractor's plain text, not the fields map. The fourth test pins down the reuse: the login route, which uses a different struct, returns the same field-error shape through the same extractor. Run the tests with cargo test and expect four passes. The invalid, valid, and malformed cases were run against this code while checking the examples for this page, and the bodies matched the ones shown above.
Common Beginner Mistakes
Returning the Inner Json Rejection Unchanged
// Wrong - the rejection types do not match
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let Json(value) = Json::<T>::from_request(req, state).await?;
Ok(ValidatedJson(value))
}
The ? operator on its own tries to return the JsonRejection as the extractor's rejection, but the declared rejection type is Response, and the two types are different. The compiler rejects this with a type error. The fix is the map_err call that converts the rejection with into_response() before the ? operator runs. The conversion is what lets a Json failure and a validation failure both come out of the same extractor as the same Response type.
Forgetting to Validate After Deserializing
// Wrong - the extractor is just Json under another name
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let Json(value) = Json::<T>::from_request(req, state)
.await
.map_err(|rejection| rejection.into_response())?;
Ok(ValidatedJson(value))
}
This compiles and runs, and it is exactly the bug the extractor exists to prevent. The wrapper adds a name but no check, so invalid data reaches the handler wrapped in a type that promises it is valid. The promise is the point of the type, and a wrapper that does not validate breaks it. The match value.validate() step is not optional. It is the reason the type exists.
Implementing FromRequestParts Instead of FromRequest
// Wrong - this trait never sees the body
impl<S, T> FromRequestParts<S> for ValidatedJson<T> { }
FromRequestParts receives only the head of the request, split off from the body. An extractor that implements it can read headers and the path, but it can never read the JSON body, so it can never build the struct. The compiler reports the problem when the implementation tries to use the body, or the handler fails to compile because the extractor cannot be built. The rule for choosing is simple: if the extractor reads the body, it implements FromRequest. If it only reads the head, it implements FromRequestParts. ValidatedJson reads the body, so the choice is FromRequest.
Adding async_trait to the Implementation
// Wrong - Axum 0.8 uses native async fn in traits
#[async_trait]
impl<S, T> FromRequest<S> for ValidatedJson<T> { }
The async_trait crate was the workaround before Rust supported async methods in traits directly. Axum 0.8 uses the native support, so the attribute is not needed, and the async_trait crate is not a dependency of the project. Adding the attribute fails to compile. Code copied from tutorials written for older Axum versions often carries it, and removing it is the fix.
A Wrapper That Skips validate Lies:
A ValidatedJson implementation that deserializes and returns without calling validate() compiles, serves requests, and silently passes invalid data to handlers that trust the type. The match value.validate() step is the whole purpose of the extractor. If it is missing, the type name is a lie.
Final Complete Example
Here is everything from this page put together: the error module, the extractor module, the library with two routes sharing the extractor, and the entry point.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use std::collections::HashMap;
use thiserror::Error;
use validator::ValidationErrors;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match &self {
AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
AppError::ValidationError(message) => {
(StatusCode::UNPROCESSABLE_ENTITY, message.clone())
}
AppError::InternalError => (
StatusCode::INTERNAL_SERVER_ERROR,
"something went wrong".to_string(),
),
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
};
let body = json!({ "error": message });
(status, Json(body)).into_response()
}
}
pub fn validation_failed(errors: &ValidationErrors) -> Response {
let mut fields: HashMap<String, Vec<String>> = HashMap::new();
for (field, kind) in errors.field_errors() {
let messages: Vec<String> = kind
.iter()
.map(|error| {
error
.message
.clone()
.map(|message| message.to_string())
.unwrap_or_else(|| error.code.to_string())
})
.collect();
fields.insert(field.to_string(), messages);
}
let body = json!({
"error": "validation failed",
"fields": fields,
});
(StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response()
}
use axum::{
Json,
extract::{FromRequest, Request},
response::{IntoResponse, Response},
};
use serde::Deserialize;
use validator::Validate;
use crate::errors::validation_failed;
pub struct ValidatedJson<T>(pub T);
impl<S, T> FromRequest<S> for ValidatedJson<T>
where
S: Send + Sync,
T: for<'de> Deserialize<'de> + Validate,
{
type Rejection = Response;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let Json(value) = Json::<T>::from_request(req, state)
.await
.map_err(|rejection| rejection.into_response())?;
match value.validate() {
Ok(()) => Ok(ValidatedJson(value)),
Err(errors) => Err(validation_failed(&errors)),
}
}
}
use axum::{Json, Router, routing::post};
use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::extractors::ValidatedJson;
pub mod errors;
pub mod extractors;
#[derive(Debug, Deserialize, Serialize, Validate)]
pub struct Signup {
#[validate(email(message = "enter a valid email address"))]
pub email: String,
#[validate(length(min = 3, max = 30, message = "name must be between 3 and 30 characters"))]
pub name: String,
#[validate(range(min = 18, max = 120, message = "age must be between 18 and 120"))]
pub age: u32,
}
#[derive(Debug, Deserialize, Serialize, Validate)]
pub struct Login {
#[validate(email(message = "enter a valid email address"))]
pub email: String,
#[validate(length(min = 8, message = "password must be at least 8 characters"))]
pub password: String,
}
pub async fn create_signup(ValidatedJson(input): ValidatedJson<Signup>) -> Json<Signup> {
Json(input)
}
pub async fn login(ValidatedJson(input): ValidatedJson<Login>) -> Json<Login> {
Json(input)
}
pub fn app() -> Router {
Router::new()
.route("/signup", post(create_signup))
.route("/login", post(login))
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run the server and send a bad signup. The answer is 422 with the field-error body. Send a bad login and the answer is the same shape with the login fields. The handler in each case is three lines long and contains no validation code, because the extractor already did the work.
Summary
The extractor turns a repeated handler chore into a property of a type. A handler that takes ValidatedJson<T> states in its signature that its input is valid, and the compiler plus the extractor together enforce that statement: the compiler enforces that T can be deserialized and validated, and the extractor enforces that this particular value passed. The single most important insight is that the guarantee moves to the boundary. Bad data is stopped where the request enters the handler, so everything inside the handler can be written as if the data is good, and the code that proves it is good lives in exactly one place.
That boundary is what validated input unlocks. Once a handler can trust its input, the rest of its work gets simpler: the code that follows the extractor no longer branches on whether the data is acceptable, and the same extractor can guard any new route that takes the same kind of input. The pattern generalises beyond validation too. Any check that belongs to the input rather than to the handler's business logic can live in an extractor, and the handler stays focused on what it should do with good data.