axum-impl-validation
axum-impl-validation
Overview
Axum has no built-in request-body validation. A handler argument of Json<T>
guarantees only that the body was syntactically valid JSON and deserialized
into T. It does NOT guarantee the values make sense: an empty name, an email
with no @, an age of 9000 all deserialize cleanly.
The idiomatic solution is the validator crate plus a small custom extractor.
validator supplies a #[derive(Validate)] macro and a .validate() method;
the custom ValidatedJson<T> extractor deserializes the body, runs
.validate(), and returns 422 Unprocessable Entity on failure. Putting the
check in the extractor makes "this value is validated" a type-level guarantee:
if the handler argument is ValidatedJson<T>, the data is already correct.
The validator crate is version 0.20. The garde crate is a context-aware
alternative covered in the decision tree below. The ValidatedJson extractor
diverges between Axum 0.7 and 0.8 by exactly one line (#[async_trait]).