Validation, errors, and HTTP responses in Laravel Rust
Continue the ticket example with GET routes. Add POST /api/tickets/preview to accept a title and return it after validation. A successful response has status 200 and carries only the title. The ticket list stays the same.
Read the request body
The Json<CreateTicket> extractor decodes the JSON body into a CreateTicket struct. Decoding checks the shape and types of the input. The application applies its own rules separately. The title is required and must be a string. Deserialize and Validate give the extractor field information and typed decoding. The handler then calls validated_title. It trims surrounding whitespace with trim(), rejects an empty result, and limits the title to 120 Unicode scalar values. chars().count() counts Rust char values. For example, ๐ฆ takes one such value and four bytes in UTF-8. A letter followed by a separate combining mark counts as two values.
LimitBody::bytes(4096) limits the entire request body, including JSON syntax and spaces. This check is separate from the title limit. In the test, JSON with the title Test and whitespace padding passes at 4096 bytes and gets 413 at 4097.
Add the preview route
Continue with your project from the routing lesson. Keep the existing Cargo.toml, Cargo.lock, and local configuration. Replace the entire src/routes/api.rs file. The GET routes and their handlers stay available. On input, the Json wrapper extracts the POST data. On output, it serializes TicketPreview. An InvalidInput value associates the validation message with title. Laravel's error handler produces the JSON response.
Download the exact Cargo.lock and save it as Cargo.lock in the demo project root. All three lessons use this file. Pass --locked so Cargo keeps the resolved versions.
use laravel::http::middleware::LimitBody;
use laravel::http::{Json, Query};
use laravel::routing::{Params, Router};
use laravel::validation::{InvalidInput, Validate};
use laravel::{Result, abort_with};
use serde::{Deserialize, Serialize};
use serde_json::json;
pub fn routes(route: &mut Router) {
route.get("/version", async || Json(json!({ "laravel": laravel::VERSION })));
route.get("/tickets", index);
route.get("/tickets/{id}", show);
route
.post("/tickets/preview", preview)
.middleware(LimitBody::bytes(TICKET_BODY_LIMIT));
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
enum Status {
Open,
Closed,
}
struct Ticket {
id: u32,
title: String,
status: Status,
}
#[derive(Debug, Serialize)]
struct TicketView {
id: u32,
title: String,
status: Status,
}
impl From<&Ticket> for TicketView {
fn from(ticket: &Ticket) -> Self {
Self {
id: ticket.id,
title: ticket.title.clone(),
status: ticket.status,
}
}
}
fn seed_tickets() -> Vec<Ticket> {
vec![
Ticket {
id: 1,
title: "Reset password".into(),
status: Status::Open,
},
Ticket {
id: 2,
title: "Update invoice".into(),
status: Status::Closed,
},
]
}
#[laravel::query]
struct TicketQuery {
// Keep an unknown nonempty value available for an explicit 400.
status: Option<String>,
}
impl TicketQuery {
fn filter(&self) -> Result<Option<Status>> {
match self.status.as_deref() {
None => Ok(None),
Some("open") => Ok(Some(Status::Open)),
Some("closed") => Ok(Some(Status::Closed)),
Some(_) => Err(abort_with(400, "Status must be open or closed.")),
}
}
}
async fn index(Query(query): Query<TicketQuery>) -> Result<Json<Vec<TicketView>>> {
let status = query.filter()?;
let tickets = seed_tickets();
Ok(Json(
tickets
.iter()
.filter(|ticket| status.is_none_or(|status| ticket.status == status))
.map(TicketView::from)
.collect(),
))
}
async fn show(Params(id): Params<u32>) -> Result<Json<TicketView>> {
positive_id(id)?;
let ticket = seed_tickets()
.into_iter()
.find(|ticket| ticket.id == id)
.ok_or_else(|| abort_with(404, "Ticket not found."))?;
Ok(Json(TicketView::from(&ticket)))
}
fn positive_id(id: u32) -> Result<()> {
if id == 0 {
return Err(abort_with(400, "Ticket ID must be positive."));
}
Ok(())
}
// The byte limit on the body applies before the title length check.
const TICKET_BODY_LIMIT: usize = 4096;
const MAX_TITLE_LENGTH: usize = 120;
#[derive(Deserialize, Validate)]
struct CreateTicket {
title: String,
}
#[derive(Serialize)]
struct TicketPreview {
title: String,
}
async fn preview(Json(input): Json<CreateTicket>) -> Result<Json<TicketPreview>> {
Ok(Json(TicketPreview {
title: input.validated_title()?,
}))
}
impl CreateTicket {
fn validated_title(&self) -> Result<String> {
let title = self.title.trim();
let problem = if title.is_empty() {
"Enter a ticket title."
} else if title.chars().count() > MAX_TITLE_LENGTH {
"The title must have at most 120 Unicode scalar values."
} else {
return Ok(title.to_owned());
};
Err(InvalidInput::new().with("title", problem).into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ticket_zero_fails_the_domain_check() {
assert!(positive_id(1).is_ok());
assert_eq!(positive_id(0).expect_err("zero").status(), 400);
}
#[test]
fn title_validation_counts_trimmed_unicode_scalars() {
let title = "๐ฆ".repeat(120);
let valid = CreateTicket {
title: format!(" {title} "),
};
assert_eq!(valid.validated_title().expect("120 scalars"), title);
let invalid = CreateTicket {
title: format!("{title}๐ฆ"),
};
assert_eq!(invalid.validated_title().expect_err("121 scalars").status(), 422);
let blank = CreateTicket {
title: "\u{00a0}\t".into(),
};
assert_eq!(blank.validated_title().expect_err("blank").status(), 422);
}
}
Compare error responses
Run these commands from the demo project root. After fetching dependencies, the build uses the local cache. The server reports the selected port. Use that port for requests to 127.0.0.1 and press Ctrl+C to stop the server.
export CARGO_TARGET_DIR="$PWD/target"
export CARGO_BUILD_BUILD_DIR="$PWD/target/build"
cargo fmt --check
cargo check --locked --offline --all-targets
cargo test --locked --offline --lib
cargo build --locked --offline
./target/debug/laravel-rust-skeleton serve --host=127.0.0.1 --port=0
The request sends two headers. Content-Type: application/json describes its body, and Accept: application/json gives the response format the client expects. This endpoint accepts JSON bodies only.
In a second terminal, enter the actual port reported by the running server. These commands connect only to 127.0.0.1.
Expect 200 for a valid title and 400 for truncated JSON. A number, a missing title, and a string of 121 ๐ฆ characters return 422. The final GET checks that the ticket list is unchanged.
read -r -p 'Port: ' PORT
BASE_URL="http://127.0.0.1:$PORT"
curl -i -sS --noproxy '*' -H 'Accept: application/json' \
-H 'Content-Type: application/json' \
--data '{"title":" Reset browser settings "}' "$BASE_URL/api/tickets/preview"
curl -i -sS --noproxy '*' -H 'Accept: application/json' \
-H 'Content-Type: application/json' \
--data '{"title":' "$BASE_URL/api/tickets/preview"
curl -i -sS --noproxy '*' -H 'Accept: application/json' \
-H 'Content-Type: application/json' \
--data '{"title":123}' "$BASE_URL/api/tickets/preview"
curl -i -sS --noproxy '*' -H 'Accept: application/json' \
-H 'Content-Type: application/json' \
--data '{}' "$BASE_URL/api/tickets/preview"
printf -v TITLE '%*s' 121 ''
TITLE=${TITLE// /๐ฆ}
curl -i -sS --noproxy '*' -H 'Accept: application/json' \
-H 'Content-Type: application/json' \
--data "{\"title\":\"$TITLE\"}" "$BASE_URL/api/tickets/preview"
curl -i -sS --noproxy '*' -H 'Accept: application/json' "$BASE_URL/api/tickets"
The excerpts below show HTTP requests and their observed responses. The port and some headers are omitted.
POST /api/tickets/preview HTTP/1.1
Host: 127.0.0.1
Accept: application/json
Content-Type: application/json
Content-Length: 38
{"title":" Reset browser settings "}
HTTP/1.1 200 OK
Content-Type: application/json
{"title":"Reset browser settings"}
When the JSON ends before the value, the framework returns 400 while reading the body.
POST /api/tickets/preview HTTP/1.1
Host: 127.0.0.1
Accept: application/json
Content-Type: application/json
Content-Length: 9
{"title":
HTTP/1.1 400 Bad Request
Content-Type: application/json
{"message":"Invalid JSON body: EOF while parsing a value at line 1 column 9"}
JSON with a number in title has valid syntax but the wrong field type. The extractor returns 422 with a top-level message and field messages in errors.title.
POST /api/tickets/preview HTTP/1.1
Host: 127.0.0.1
Accept: application/json
Content-Type: application/json
Content-Length: 13
{"title":123}
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{"message":"The title field must be a string.","errors":{"title":["The title field must be a string."]}}
Both layers can return 422. On the verified version, the extractor rejects a missing, empty, or whitespace-only title with The title field is required.. A string of 121 scalar values reaches validated_title, which returns a field error for title.
POST /api/tickets/preview HTTP/1.1
Host: 127.0.0.1
Accept: application/json
Content-Type: application/json
Content-Length: 497
{"title": "๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ๐ฆ"}
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{"message":"The title must have at most 120 Unicode scalar values.","errors":{"title":["The title must have at most 120 Unicode scalar values."]}}
A missing Content-Type or a URL-encoded form gets 415. A request over the configured body limit gets 413. Those rejections and the syntax error carry a message. The verified 422 responses also carry errors.title. All these verified responses have Content-Type: application/json.
Summary
Typed decoding gives the handler a CreateTicket. The application rule turns its title into a string ready for the response. In the lesson on async and shared state, the same check runs before insertion, and the client receives 201 once the record exists.
References
- Validation and responses in the Laravel Rust 0.1.4 source package โ
docs/validation.md,docs/errors.md,docs/responses.md. - Source package for laravel-rust-http 0.1.4 โ
src/validation/request.rs,src/validation/invalid_input.rs,src/http/middleware/limits.rs.