Skip to content

Validation ​

With the garde feature, one struct gives you deserialization, validation and the schema, like t.Object in Elysia.

toml
axum-autodoc = { version = "0.2", features = ["garde"] }
garde = { version = "0.23", features = ["derive", "email"] }

One struct, three jobs ​

rust
#[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 ​

ExtractorReadsDocuments
Body<T>a JSON bodythe request body, 400, 413 and 415
Query<T>the query stringthe query parameters and 400
Params<T>path parametersthe path parameters and 400
Headers<T>request headersone header parameter per field and 400
Cookies<T>the Cookie headerone cookie parameter per field and 400
Upload<T>a multipart formthe form, 400, 413 and 415, see Uploads

Each one deserializes, then runs T::validate, and only then calls your handler.

rust
#[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:

json
{ "error": "validation", "issues": [{ "path": "email", "message": "not a valid email: value is missing `@`" }] }
errorStatus
validation400
malformed400
unsupported_media_type415
payload_too_large413
unauthorized401

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.

rust
#[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:

rust
#[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>,
}
rust
#[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 Cookie header 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: 3 fills a u8, a repeated header fills a Vec and true fills a bool.
  • A missing required value or one that cannot be coerced answers 400 with error: "malformed", and a failed rule answers 400 with error: "validation", both as RequestRejection.

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.

Released under the MIT or Apache-2.0 license.