Course › Week 5 · Axum microservice › Day 2 · lesson 30 of 42 · 30 min reading + 45–60 min practice
JSON in and out, with validation
Request and response bodies as types, and validation like a Form Request.
On this page
Today’s endpoint is the front door of this week’s service: POST /batches, which Laravel will call to hand over a batch of evaluations. Its body must be checked before anything else happens, the job a Form Request does in Laravel.
By the end, a bad request gets a 422 that Laravel’s HTTP client can read with the same code it uses for Laravel’s own APIs: a message and an errors map from field to messages.
1. Json in, Json out
Json(batch): Json<NewBatch> reads the body and decodes it with serde, the same Json that wraps responses. The status of a created resource is 201, returned as the first item of a tuple.
One rule of axum: the extractor that reads the body must be the last argument, because the body can only be read once.
use std::error::Error;
use axum::http::StatusCode;
use axum::routing::post;
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use tokio::net::TcpListener;
#[derive(Deserialize)]
struct NewBatch {
evaluation_ids: Vec<i64>,
requested_by: String,
}
#[derive(Serialize)]
struct Accepted {
evaluations: usize,
requested_by: String,
}
async fn store(Json(batch): Json<NewBatch>) -> (StatusCode, Json<Accepted>) {
let accepted = Accepted {
evaluations: batch.evaluation_ids.len(),
requested_by: batch.requested_by,
};
(StatusCode::CREATED, Json(accepted))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new().route("/batches", post(store));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
}
HTTP/1.1 201 Created
content-type: application/json
content-length: 42
{"evaluations":2,"requested_by":"nightly"}HTTP/1.1 415 Unsupported Media Type
content-type: text/plain; charset=utf-8
content-length: 54
Expected request with `Content-Type: application/json`HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
content-length: 101
Failed to parse the request body as JSON: requested_by: EOF while parsing a value at line 1 column 43HTTP/1.1 422 Unprocessable Entity
content-type: text/plain; charset=utf-8
content-length: 142
Failed to deserialize the JSON body into the target type: evaluation_ids: invalid type: string "1042", expected a sequence at line 1 column 25Three bad requests, three different answers, none from your code: no Content-Type: application/json is 415, JSON that does not parse is 400, JSON of the wrong shape is 422, each with a sentence. The rules are right; the bodies are plain text, which a Laravel client would not expect. Section 5 turns them into JSON.
2. Rules the type cannot express
A Vec<i64> accepts an empty list, and a String accepts "". The validator crate adds rules as attributes, the way Laravel’s rules() array does: #[derive(Validate)] writes a validate() method that checks them all and returns every failure, not only the first.
| Laravel rule | validator attribute |
|---|---|
required|array|min:1|max:500 | #[validate(length(min = 1, max = 500))] on a Vec |
string|max:100 | #[validate(length(min = 1, max = 100))] on a String |
nullable|email | #[validate(email)] on an Option<String>: checked only when present |
integer|between:1,365 | #[validate(range(min = 1, max = 365))] |
use std::error::Error;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{Json, Router};
use serde::Deserialize;
use tokio::net::TcpListener;
use validator::Validate;
#[derive(Deserialize, Validate)]
struct NewBatch {
#[validate(length(min = 1, max = 500, message = "Send between 1 and 500 evaluation ids."))]
evaluation_ids: Vec<i64>,
#[validate(length(
min = 1,
max = 100,
message = "The requested by field must be 1 to 100 characters."
))]
requested_by: String,
#[validate(email(message = "The notify field must be a valid email address."))]
notify: Option<String>,
}
async fn store(Json(batch): Json<NewBatch>) -> Response {
if let Err(errors) = batch.validate() {
return (StatusCode::UNPROCESSABLE_ENTITY, Json(errors)).into_response();
}
let note = match &batch.notify {
Some(email) => format!(", notifying {email}"),
None => String::new(),
};
let text = format!(
"{} evaluations for {}{note}",
batch.evaluation_ids.len(),
batch.requested_by
);
(StatusCode::CREATED, text).into_response()
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new().route("/batches", post(store));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
}
HTTP/1.1 201 Created
content-type: text/plain; charset=utf-8
content-length: 53
2 evaluations for nightly, notifying sara@example.comHTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 382
{"notify":[{"code":"email","message":"The notify field must be a valid email address.","params":{"value":"sara"}}],"evaluation_ids":[{"code":"length","message":"Send between 1 and 500 evaluation ids.","params":{"value":[],"min":1,"max":500}}],"requested_by":[{"code":"length","message":"The requested by field must be 1 to 100 characters.","params":{"value":"","min":1,"max":100}}]}All three rules failed, and all three are reported. ValidationErrors serialises as it is, which is honest but not the shape anyone’s client expects: codes, params, the rejected value, and the fields in no fixed order, because it keeps them in a HashMap. The next section reshapes it.
The handler returns Response, the type every IntoResponse turns into, because its two branches return different types. .into_response() on each branch makes them the same.
3. A 422 the way Laravel sends it
Laravel’s validation response is {"message": "<first error>", "errors": {"field": ["messages"]}}. invalid() builds exactly that from ValidationErrors: field_errors() gives the failures per field, and each has the message from its attribute. A BTreeMap keeps the fields in alphabetical order, so the body is the same on every request.
use std::collections::BTreeMap;
use std::error::Error;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use tokio::net::TcpListener;
use validator::{Validate, ValidationErrors};
#[derive(Deserialize, Validate)]
struct NewBatch {
#[validate(length(min = 1, max = 500, message = "Send between 1 and 500 evaluation ids."))]
evaluation_ids: Vec<i64>,
#[validate(length(
min = 1,
max = 100,
message = "The requested by field must be 1 to 100 characters."
))]
requested_by: String,
#[validate(email(message = "The notify field must be a valid email address."))]
notify: Option<String>,
}
/// The body Laravel sends with a 422: the first message, and every message per field.
#[derive(Serialize)]
struct Invalid {
message: String,
errors: BTreeMap<String, Vec<String>>,
}
fn invalid(errors: &ValidationErrors) -> Response {
let mut fields: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (field, list) in errors.field_errors() {
let messages = list
.iter()
.map(|e| {
e.message
.as_deref()
.unwrap_or("The value is invalid.")
.to_string()
})
.collect();
fields.insert(field.to_string(), messages);
}
let message = fields
.values()
.next()
.and_then(|messages| messages.first())
.cloned()
.unwrap_or_else(|| String::from("The given data was invalid."));
let body = Invalid {
message,
errors: fields,
};
(StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response()
}
async fn store(Json(batch): Json<NewBatch>) -> Response {
if let Err(errors) = batch.validate() {
return invalid(&errors);
}
let notify = batch.notify.as_deref().unwrap_or("nobody");
let text = format!(
"{} evaluations for {}, notifying {notify}",
batch.evaluation_ids.len(),
batch.requested_by
);
(StatusCode::CREATED, text).into_response()
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new().route("/batches", post(store));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
}
HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 255
{"message":"Send between 1 and 500 evaluation ids.","errors":{"evaluation_ids":["Send between 1 and 500 evaluation ids."],"notify":["The notify field must be a valid email address."],"requested_by":["The requested by field must be 1 to 100 characters."]}}HTTP/1.1 201 Created
content-type: text/plain; charset=utf-8
content-length: 43
2 evaluations for nightly, notifying nobodyThe Laravel side can now treat this service like any Laravel API: $response->json('errors.evaluation_ids.0') works unchanged.
4. ValidatedJson: a Form Request for every handler
Calling validate() at the top of every handler is the kind of line that one handler forgets. An extractor of your own does it once: ValidatedJson<T> reads the body with Json<T>, validates it, and only then hands it to the handler. A handler that asks for ValidatedJson<NewBatch> cannot receive an invalid batch, the same promise a type-hinted Form Request makes.
An extractor implements axum’s FromRequest trait: one async function that gets the request and returns the value, or a Rejection that is sent as the response. Inside, it also turns axum’s own plain-text rejections from section 1 into JSON with the same status.
use std::collections::BTreeMap;
use std::error::Error;
use axum::extract::{FromRequest, Request};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{Json, Router};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tokio::net::TcpListener;
use validator::{Validate, ValidationErrors};
#[derive(Deserialize, Validate)]
struct NewBatch {
#[validate(length(min = 1, max = 500, message = "Send between 1 and 500 evaluation ids."))]
evaluation_ids: Vec<i64>,
#[validate(length(
min = 1,
max = 100,
message = "The requested by field must be 1 to 100 characters."
))]
requested_by: String,
#[validate(email(message = "The notify field must be a valid email address."))]
notify: Option<String>,
}
/// The body Laravel sends with a 422: the first message, and every message per field.
#[derive(Serialize)]
struct Invalid {
message: String,
errors: BTreeMap<String, Vec<String>>,
}
fn invalid(errors: &ValidationErrors) -> Response {
let mut fields: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (field, list) in errors.field_errors() {
let messages = list
.iter()
.map(|e| {
e.message
.as_deref()
.unwrap_or("The value is invalid.")
.to_string()
})
.collect();
fields.insert(field.to_string(), messages);
}
let message = fields
.values()
.next()
.and_then(|messages| messages.first())
.cloned()
.unwrap_or_else(|| String::from("The given data was invalid."));
let body = Invalid {
message,
errors: fields,
};
(StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response()
}
#[derive(Serialize)]
struct Message {
message: String,
}
/// A JSON body that has passed its validation rules.
struct ValidatedJson<T>(T);
impl<T, S> FromRequest<S> for ValidatedJson<T>
where
T: DeserializeOwned + Validate,
S: Send + Sync,
{
type Rejection = Response;
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
let Json(value) = Json::<T>::from_request(request, state)
.await
.map_err(|rejection| {
let body = Message {
message: rejection.body_text(),
};
(rejection.status(), Json(body)).into_response()
})?;
value.validate().map_err(|errors| invalid(&errors))?;
Ok(ValidatedJson(value))
}
}
async fn store(ValidatedJson(batch): ValidatedJson<NewBatch>) -> (StatusCode, String) {
let notify = batch.notify.as_deref().unwrap_or("nobody");
let text = format!(
"{} evaluations for {}, notifying {notify}",
batch.evaluation_ids.len(),
batch.requested_by
);
(StatusCode::CREATED, text)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new().route("/batches", post(store));
let listener = TcpListener::bind("127.0.0.1:3000").await?;
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
}
HTTP/1.1 201 Created
content-type: text/plain; charset=utf-8
content-length: 43
2 evaluations for nightly, notifying nobodyHTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 123
{"message":"Send between 1 and 500 evaluation ids.","errors":{"evaluation_ids":["Send between 1 and 500 evaluation ids."]}}HTTP/1.1 415 Unsupported Media Type
content-type: application/json
content-length: 68
{"message":"Expected request with `Content-Type: application/json`"}HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 158
{"message":"Failed to deserialize the JSON body into the target type: evaluation_ids: invalid type: string \"1042\", expected a sequence at line 1 column 25"}store has no validation code left, and every failure is now JSON with the right status. impl<T, S> FromRequest<S> for ValidatedJson<T> where … reads: “for any body type T that can be decoded and validated, and any state S, here is how to extract a ValidatedJson<T>”. The where clause is the list of bounds from the traits lesson, written after the signature because it is long.
DeserializeOwned is serde’s bound for “can be decoded without borrowing from the input”, which a request body that is gone after reading requires.
The same thing as a Form Request
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
final class StoreBatchRequest extends FormRequest
{
/** @return array<string, list<string>> */
public function rules(): array
{
return [
'evaluation_ids' => ['required', 'array', 'min:1', 'max:500'],
'evaluation_ids.*' => ['integer'],
'requested_by' => ['required', 'string', 'max:100'],
'notify' => ['nullable', 'email'],
];
}
}
The same rules, and the same promise: the controller never sees invalid input. The difference is the evaluation_ids.* line, which Rust does not need: Vec<i64> already refuses a list with a string in it, before the rules run. And after validation, Laravel hands you $request->validated(), still an array; axum hands you a NewBatch, with types.
PracticeThe validator docs, and a rule of your own
Skim the validator README: the list of built-in rules, and custom ones.
Exercise: no duplicate ids
Laravel’s distinct rule rejects an array with duplicates. Add the same to evaluation_ids with #[validate(custom(function = "distinct_ids"))] and a function fn distinct_ids(ids: &[i64]) -> Result<(), ValidationError>. Return ValidationError::new("distinct").with_message("The evaluation ids field has a duplicate value.".into()) when one id appears twice.
Show the rule
#[derive(Deserialize, Validate)]
struct NewBatch {
#[validate(
length(min = 1, max = 500, message = "Send between 1 and 500 evaluation ids."),
custom(function = "distinct_ids")
)]
evaluation_ids: Vec<i64>,
// … the other fields as before
}
fn distinct_ids(ids: &[i64]) -> Result<(), ValidationError> {
let mut sorted = ids.to_vec();
sorted.sort_unstable();
if sorted.windows(2).any(|pair| pair[0] == pair[1]) {
return Err(ValidationError::new("distinct")
.with_message("The evaluation ids field has a duplicate value.".into()));
}
Ok(())
}
windows(2) walks a slice two items at a time, overlapping: after sorting, a duplicate is always next to its twin. Add ValidationError to the validator import.
Remember
- The body extractor goes last; validate before anything else, and answer 422 in the shape Laravel’s client already reads.
Tomorrow: shared state, so every handler can reach the database pool and the analysis client.