Validation
With the garde feature, one struct gives you deserialization, validation and the schema, like t.Object in Elysia.
axum-autodoc = { version = "0.2", features = ["garde"] }
garde = { version = "0.23", features = ["derive", "email"] }One struct, three jobs
#[derive(Deserialize, Validate, JsonSchema)]
struct NewUser {
#[garde(length(min = 1, max = 50))]
name: String,
#[garde(email)]
email: String,
}schemars reads #[garde(...)] directly, so length, range, email, url, pattern and friends show up in the schema as minLength, maximum, format, and so on. The rules you validate with are exactly the rules your clients see.
Validated extractors
| Extractor | Reads | Documents |
|---|---|---|
Body<T> | a JSON body | the request body, 400, 413 and 415 |
Query<T> | the query string | the query parameters and 400 |
Params<T> | path parameters | the path parameters and 400 |
Headers<T> | request headers | one header parameter per field and 400 |
Cookies<T> | the Cookie header | one cookie parameter per field and 400 |
Upload<T> | a multipart form | the form, 400, 413 and 415, see Uploads |
Each one deserializes, then runs T::validate, and only then calls your handler.
#[api(summary = "Create a user")]
async fn create_user(Auth(_claims): Auth<Claims>, Body(body): Body<NewUser>) -> Created<User> {
Created(User {
id: 1,
name: body.name,
nickname: Some(body.email),
})
}Errors
Failures respond with a RequestRejection body, also published in the document:
{ "error": "validation", "issues": [{ "path": "email", "message": "not a valid email: value is missing `@`" }] }error | Status |
|---|---|
validation | 400 |
malformed | 400 |
unsupported_media_type | 415 |
payload_too_large | 413 |
unauthorized | 401 |
Arrays in the query string
The validated Query<T> reads repeated keys as arrays, so ?tag=a&tag=b fills a Vec<String>. That is also how the TypeScript client sends arrays.
#[derive(Deserialize, Validate, JsonSchema)]
struct Search {
#[garde(length(min = 1))]
tag: Vec<String>,
}axum's own Query
axum's Query<T> cannot read arrays. Use the validated one, or axum_extra::extract::Query, for those.
Headers and cookies
Headers<T> and Cookies<T> read a struct from the request the same way Query<T> does, then run T::validate:
#[derive(Debug, Deserialize, Validate, JsonSchema)]
pub struct ClientInfo {
#[serde(rename = "x-request-id")]
#[garde(length(min = 8))]
pub request_id: String,
#[serde(rename = "x-retries")]
#[garde(range(max = 5))]
pub retries: Option<u8>,
}
#[derive(Debug, Deserialize, Validate, JsonSchema)]
pub struct Session {
#[garde(length(min = 8))]
pub sid: String,
#[garde(range(min = 1))]
pub theme: Option<u32>,
}#[api(
summary = "Read the session",
description = "The session comes from the `sid` and `theme` cookies, the caller from two headers."
)]
pub async fn session(
Headers(client): Headers<ClientInfo>,
Cookies(session): Cookies<Session>,
) -> Json<SessionResponse> {
Json(SessionResponse {
sid: session.sid,
theme: session.theme.unwrap_or(0),
request_id: client.request_id,
retries: client.retries.unwrap_or(0),
})
}Each field becomes one in: header or in: cookie parameter, required when the schema says so, and the route gets the 400 response.
- Header names are matched case-insensitively against the field names, so name the field the way you want the header documented, with
#[serde(rename = "x-request-id")]. A#[serde(flatten)]field only matches lowercase names. - Cookie names are case-sensitive. Every
Cookieheader is read, split on;, and each pair on its first=. Values are not percent-decoded. - Values are coerced like a query string, so
x-retries: 3fills au8, a repeated header fills aVecandtruefills abool. - A missing required value or one that cannot be coerced answers
400witherror: "malformed", and a failed rule answers400witherror: "validation", both asRequestRejection.
Cookies in the TypeScript client
A browser manages cookies, so the client does not send them. They stay in the JSDoc of the call. Headers are typed in options.headers.