axum-autodocOpenAPI, inferred.
Write plain axum handlers. Get an OpenAPI 3.2 document, validation, auth and a typed TypeScript client, straight from their signatures.
Write plain axum handlers. Get an OpenAPI 3.2 document, validation, auth and a typed TypeScript client, straight from their signatures.
The path parameter, the success body and every error your type can return are read from the function itself. Change the code and the docs follow.
#[api(summary = "Find a user")]
async fn find_user(
Path(id): Path<u32>,
) -> Result<Json<User>, FindUserError> {
match id {
0 => Err(FindUserError::NotFound(id)),
id => Ok(Json(User {
id,
name: "Ann".to_string(),
nickname: None,
})),
}
}
impl DocError for FindUserError {
fn responses() -> Vec<(u16, &'static str)> {
vec![(404, "user not found")]
}
fn describe(cx: &mut DocContext<'_>) {
cx.error_responses::<ErrorResponse>(
&Self::responses(),
);
}
}operationId: find_user
summary: Find a user
tags: [Users]
parameters:
- name: id
in: path
required: true
schema:
type: integer
format: uint32
minimum: 0
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/User"
"400":
description: Bad Request
content:
text/plain:
schema: { type: string }
"404":
description: user not found
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorResponse"
security: [] Only the two marked lines were written by hand, in #[api] and the group's tag. Everything else was inferred.
Call .openapi(..) on the router and these are served next to your API, on the same paths as @elysiajs/openapi.
/openapiScalar API reference, or Swagger UI/openapi/jsonOpenAPI 3.2 document/client.tsTyped TypeScript client schemars reads #[garde(..)] directly, so the rules you validate with are the rules your clients see.
#[derive(Deserialize, Validate, JsonSchema)]
struct NewUser {
#[garde(length(min = 1, max = 50))]
name: String,
#[garde(email)]
email: String,
}
#[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),
})
}type: object
required: [name, email]
properties:
name:
type: string
minLength: 1
maxLength: 50
email:
type: string
format: email{
"error": "validation",
"issues": [
{
"path": "email",
"message": "not a valid email: value is missing `@`"
}
]
} Each call returns a union built from the statuses that route can really return. Narrow on status and TypeScript knows the rest.
let app = ApiRouter::new()
.openapi(openapi())
.group("/users", |users| {
users
.tag("Users")
.get("/", list_users)
.post("/", create_user)
.get("/{id}", find_user)
})
.try_finish(state)?;import { createClient } from "./api";
const api = createClient("http://localhost:3000", {
headers: () => ({
authorization: `Bearer ${token}`,
}),
});
const user = await api.users({ id: 1 }).get();
if (user.status === 200) user.data.name;
else if (user.status === 404) user.error.value.message;Auth<C> verifies a JWT and documents bearerAuth and the 401. The response never says why a token was refused.
axum's own rejections, validation failures and your typed errors all land in the document.
Implement DocInput or DocError once and every route that uses the type is documented.
One environment variable leaves the documentation engine out of the binary. Your code compiles unchanged.
If a handler uses an extractor or return type that cannot be documented, it does not compile, so the docs never drift from the code.
| axum-autodoc | utoipa | aide | |
|---|---|---|---|
| No per-handler annotation | |||
| Validation from the same schema | |||
| Every status that can happen | |||
| Typed TypeScript client |
One dependency. Plain handlers. A spec, a reference page and a client on the first run.
cargo add axum-autodoc --features garde,jwt