Expand description
§axum-autodoc
Elysia-style automatic OpenAPI for axum. Handlers stay plain functions. The docs, the validation errors, the security requirements and a typed TypeScript client are all inferred from their signatures.
Status:
0.2. The API may still change before1.0.
Documentation · API reference · Changelog
Every Rust snippet below is taken from the examples in
axum-autodoc/examples,
which CI compiles.
#[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 })),
}
}
#[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) })
}
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)?;| Route | Serves |
|---|---|
/openapi | Scalar API reference (or Swagger UI) |
/openapi/json | OpenAPI 3.2 document |
/client.ts | Typed TypeScript client (feature ts) |
§Why
| axum-autodoc | utoipa | aide | |
|---|---|---|---|
| No per-handler annotation | ✅ | ❌ | ✅ |
| Validation from the same schema | ✅ | ❌ | ❌ |
| Every status that can happen | ✅ | ❌ | ❌ |
| Typed TypeScript client | ✅ | ❌ | ❌ |
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.
§Install
[dependencies]
axum-autodoc = { version = "0.2", features = ["garde", "jwt"] }
schemars = "1"
garde = { version = "0.23", features = ["derive", "email"] }schemars derives the schemas and garde the validation rules in your own crate; enable
the garde features your rules use (email, url, pattern, …).
| Feature | Default | Adds |
|---|---|---|
macros | ✅ | #[api] for summaries, descriptions, tags and more |
ts | ✅ | TypeScript client at /client.ts and export_ts |
garde | Body<T>, Query<T>, Params<T> with validation | |
jwt | Auth<C> bearer extractor and JwtKeys | |
multipart | Upload<T> and File for multipart forms (adds garde) | |
sse | EventStream<T> for server-sent events | |
ws | Socket<In, Out> for typed WebSockets | |
test-client | ApiRouter::test_client for in-memory tests | |
extra | documents the axum-extra 0.12 extractors and responses |
§Compatibility
| Needs | Supported |
|---|---|
| axum | 0.8 (axum = "0.8", so any 0.8.x) |
| axum-extra | 0.12, behind the extra feature |
| Rust | 1.88 or later (MSRV) |
| OpenAPI document | 3.2.0 by default; .openapi_version("3.1.0") or "3.0.3" write that version instead |
The coverage table lists every axum and axum-extra type and what it documents.
§What gets inferred
| In the signature | In the document |
|---|---|
Json<T>, Form<T>, String, Bytes | request body, plus axum’s own rejections (400, 413, 415, 422 as plain text) |
Path<T> / Params<T> | path parameters: scalars, structs by field name, tuples by position, #[serde(flatten)] |
Query<T> (axum or validated) | query parameters with required taken from the schema, plus 400 |
Body<T>, Query<T>, Params<T> | 400 (and 413, 415 for bodies) with RequestRejection |
Auth<C> / Option<Auth<C>> | bearerAuth security scheme, security (required schemes in one object, Either sides and Option as alternatives, {} only when nothing is required) and 401 |
Headers<T>, Cookies<T> | one header or cookie parameter per field, plus 400 |
Upload<T> | multipart/form-data body, File fields as binary strings, plus 400, 413, 415 |
Socket<In, Out> | 101 and x-autodoc-websocket with the schema of each direction |
Json<T> / Created<T> / NoContent | 200 / 201 / 204 |
Status<C, T> | the responses of T with its success status moved to C |
StatusCode, (StatusCode, T) | a default response (the status is only known at run time) |
EventStream<T> | 200 as text/event-stream with each event’s itemSchema (3.2; x-autodoc-item-schema under 3.1 and 3.0) |
Redirect / Response | 303, 307, 308 / nothing |
Result<T, E: DocError> | the success response plus every status E lists |
| handler function name | operationId (deduplicated across modules) and a default summary |
Schemas live once under #/components/schemas and are referenced with $ref.
Request types are described the way serde deserializes them and response types the way
serde serializes them, so an Option<T> field is optional in a request body but required
and nullable in a response. When one type is used in both directions and the two shapes
differ, the request side is named …Input (for example Note and NoteInput).
§Documentation page
The defaults follow @elysiajs/openapi:
fn openapi() -> OpenApi {
OpenApi::new()
.title("User API")
.version("1.2.0")
.description("Everything about users")
.license("MIT")
.server("https://api.example.com")
.tag("Users", "User management")
.path("/openapi")
.spec_path("/openapi/json")
.provider(Provider::Scalar(ScalarRenderer::default().version("1.79.0")))
.exclude_paths(["/internal/*"])
.exclude_methods(["OPTIONS"])
.exclude_tags(["Internal"])
.terms_of_service("https://example.com/terms")
.contact("API team", Some("https://example.com"), Some("api@example.com"))
.external_docs("https://docs.example.com", Some("Guides"))
.extension("logo", serde_json::json!({ "url": "/logo.svg" }))
.export_ts("web/api.ts")
}Scalar defaults to @scalar/api-reference 1.79.0 and Swagger UI to swagger-ui-dist 5.35.0,
both pinned so a new CDN release cannot break the page; .version(..) and .cdn(..) change
them. .openapi_version("3.1.0") (the default document is OpenAPI 3.2.0), .license_url(..) and .embed_spec(true) (the document
inside the page instead of fetched from spec_path) are there too. Use
Provider::swagger_ui() for Swagger UI (with SwaggerRenderer::default().theme(..) and
.dark_theme(..) for custom stylesheets) or Provider::None to serve only the JSON, and
.enabled(false) to switch every documentation route off at runtime.
§Turning documentation off at compile time
To keep the documentation engine out of the binary entirely, set AXUM_AUTODOC_ENABLED
when building:
# .cargo/config.toml
[env]
AXUM_AUTODOC_ENABLED = "false"AXUM_AUTODOC_ENABLED=false cargo build --releaseWith false, the spec builder, schema generator, Scalar and Swagger pages, TypeScript client
and #[api] registration are not compiled. ApiRouter becomes a thin wrapper over
axum::Router, and #[api] leaves the function untouched. Your code compiles unchanged:
the builders, DocError, DocContext and Detail are still there and do nothing, and
Body, Query, Params and Auth still validate and authenticate. Only the APIs that
read the generated document (ApiRouter::document, typescript_client,
DocContext::operation and the openapi module’s document types) are unavailable.
axum_autodoc::ENABLED tells you which mode was compiled. Accepted values are
true/false, 1/0, yes/no and on/off; the default is true.
§Route details
#[api] attaches metadata without changing the handler. It also reads /// doc comments
(the first line becomes the summary, the rest the description) and #[deprecated].
Without either, the summary comes from the function name (list_users → “List users”).
#[api(tag = "Users", summary = "List users", description = "Newest first")]
async fn list_users() -> Json<Vec<User>> {
Json(Vec::new())
}
#[api(response(429, "Too many requests"))]
async fn search<E: SearchEngine>(Query(query): Query<Search>) -> Json<Vec<String>> {
Json(E::hits(&query.tag))
}
#[api(tags(Users, Admin), operation_id = "purgeUsers", deprecated)]
async fn purge() -> NoContent {
NoContent
}
#[api(hide)]
async fn health() -> &'static str {
"ok"
}Generic handlers work too, wherever they are declared. #[api] cannot be placed on methods
inside an impl block; use .detail(..) for those. Without the macro, Elysia detail style:
let app = ApiRouter::new()
.get("/tenant", tenant)
.detail(&Detail::new().summary("Echo the tenant").tag("Tenants"))
.group("/admin", |admin| {
admin
.guard(Detail::new().tag("Admin"))
.delete("/users", purge)
});Detail also takes .description(..), .operation_id(..), .deprecated(), .hide(),
.security(..) and .response(status, description). Inside group, a route at "/" maps
to the group prefix itself.
§Validation (garde)
One struct gives you deserialization, validation and the schema, like t.Object in Elysia.
schemars reads #[garde(...)] directly, so length, range, email, url,
pattern and friends show up as minLength, maximum, format, and so on.
#[derive(Deserialize, Validate, JsonSchema)]
struct NewUser {
#[garde(length(min = 1, max = 50))]
name: String,
#[garde(email)]
email: String,
}Failures respond with 400:
{ "error": "validation", "issues": [{ "path": "email", "message": "not a valid email: value is missing `@`" }] }error is one of validation, malformed, unsupported_media_type, payload_too_large
or unauthorized. The validated Query<T> reads repeated keys as arrays (?tag=a&tag=b
into Vec<String>), which is what the TypeScript client sends. axum’s own Query<T> cannot
read arrays; use the validated one, or axum_extra::extract::Query, for those.
A handler cannot return impl IntoResponse, since nothing says what it holds. Return Response
when you build the response by hand, which documents nothing, and add its statuses with
#[api(response(..))]:
#[api(response(200, "The service banner"))]
async fn banner() -> Response {
(StatusCode::OK, "user-api").into_response()
}§Headers and cookies
Headers<T> and Cookies<T> read a struct from the request and validate it like Query<T>.
Header names match case-insensitively, so name each field with #[serde(rename = "x-request-id")]. A #[serde(flatten)] field only matches lowercase names:
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),
})
}§Uploads (multipart)
Upload<T> reads a multipart form into one validated struct; a File field keeps the file
name, content type and bytes. It documents the body as multipart/form-data plus 400,
413 and 415, and the TypeScript client sends a FormData.
#[derive(Debug, Deserialize, Validate, JsonSchema)]
pub struct NewAvatar {
#[garde(skip)]
pub image: File,
#[garde(length(max = 100))]
pub caption: Option<String>,
}§Event streams (sse)
EventStream<T> sends each item of a stream as one JSON event and documents the item
schema, which the TypeScript client reads as an AsyncIterable<T> (for await).
EventStream::new(events).keep_alive(KeepAlive::default())§WebSockets (ws)
Socket<In, Out> upgrades the request and types the JSON messages in both directions, and
the TypeScript client gets a typed subscribe().
pub async fn chat(socket: Socket<ChatIn, ChatOut>) -> SocketUpgrade {
socket.on_upgrade(converse)
}§Auth (jwt)
#[derive(Clone)]
struct AppState {
jwt: JwtKeys,
}
impl FromRef<AppState> for JwtKeys {
fn from_ref(state: &AppState) -> Self {
state.jwt.clone()
}
}
#[api(summary = "Who am I", description = "Works with or without a token")]
async fn me(auth: Option<Auth<Claims>>) -> Json<Option<String>> {
Json(auth.map(|Auth(claims)| claims.sub))
}JwtKeys::hs256(secret) builds the keys and jwt.sign(&claims) issues a token. Missing or
invalid tokens get 401 with WWW-Authenticate: Bearer and the same body whatever the
reason, so the response never says why a token was refused. With Option<Auth<C>>, no
Authorization header or a scheme other than Bearer is None, and an invalid bearer token
is still 401. When any route needs auth, every public route is marked with an explicit
security: [].
Validation checks the signature and exp by default but not who the token is for. Set the
audience and issuer you expect, as examples/readme.rs does:
JwtKeys::hs256(b"change-me")?.with_validation(|validation| {
validation.set_audience(&["user-api"]);
validation.set_issuer(&["https://auth.example.com"]);
})Other keys are built with JwtKeys::rsa_pem, ec_pem and ed_pem (RS, ES and EdDSA), and a
service that only checks tokens uses rsa_verifier_pem, ec_verifier_pem or ed_verifier_pem
with the public key alone (examples/jwt_keys.rs):
fn verifier_keys(public_pem: &[u8]) -> Result<JwtKeys, InvalidJwtSecret> {
JwtKeys::rsa_verifier_pem(public_pem, Algorithm::RS256)
}For an API key in a header, write an extractor whose DocInput calls
cx.security_scheme("apiKeyAuth", SecurityScheme::ApiKey { .. }); the guide has the whole recipe.
§Testing (test-client)
ApiRouter::test_client(state) calls the routes in memory and fails a test when a route
answers with a status its operation does not document.
let created = client
.post("/users")
.json(&json!({ "name": "Ann", "email": "ann@example.com" }))
.send()
.await;
assert_eq!(created.status(), StatusCode::CREATED);§TypeScript client (ts)
OpenApi::export_ts("web/api.ts") writes the client in debug builds only. The same source
is always served at /client.ts (move it with .client_path(Some("/sdk.ts")), disable it
with .client_path(None)).
import { createClient } from "./api";
const api = createClient("http://localhost:3000", {
headers: () => ({ authorization: `Bearer ${token}` }),
});
const users = await api.users.get();
const created = await api.users.post({ name: "Ann", email: "ann@example.com" });
const user = await api.users({ id: 1 }).get();
if (user.status === 200) user.data.name;
else if (user.status === 404) user.error.value.message;Each call returns a discriminated union of { data, error, status } built from the
statuses that route can really return. Bodies are sent in the route’s media type: JSON,
application/x-www-form-urlencoded for Form<T>, plain text for String, and a
Blob, ArrayBuffer or string for Bytes, and FormData for Upload<T>. An event stream is an
AsyncIterable to read with for await, and a WebSocket route has a typed subscribe(). Summaries, descriptions and deprecated become
JSDoc, documented header parameters are typed in options.headers, and a path segment that
is also an HTTP method name, or is named subscribe, gets a $ prefix (/items/get becomes api.items.$get.get()).
The output passes tsc --strict with exactOptionalPropertyTypes and
noUncheckedIndexedAccess.
§Finishing the router
finish(state) returns the axum::Router. If exporting the TypeScript file fails, it keeps
serving and prints the error to stderr. try_finish(state) returns
Result<Router, axum_autodoc::error::FinishError> instead, for a build that should stop on
that error. document() returns the assembled openapi::Document without serving anything,
and typescript_client(&document) renders the client from it.
§Your own extractors and responses
impl DocInput for TenantId {
fn describe(cx: &mut DocContext<'_>) {
cx.response(403, "tenant is missing or suspended");
}
}
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());
}
}DocContext also offers body, json_response, content_response, path_params_from,
query_params_from, security_scheme, require_security, input_schema, output_schema and
direct access to the openapi::Operation. Error types live in axum_autodoc::error.
§Architecture
The crate is hexagonal. Dependencies point inward:
adapters (axum, schemars, serde_json, garde, jsonwebtoken, Scalar, Swagger UI, TypeScript, fs)
↓
application (document assembly, publishing, authentication)
↓
domain (typed OpenAPI model, value objects, errors, ports)The domain depends only on serde and thiserror. Renderers, serializers, token
verifiers and file writers are ports, so each can be swapped or tested with a mock.
Only the root items, openapi and error are public.
§Examples
examples/users
is a complete service built the same way: domain, use cases with typed errors, an in-memory
repository, validated DTOs, JWT auth and an exported client.
cargo run -p axum-autodoc --example users --all-features
open http://localhost:3000/openapie2e lints its spec with Redocly,
type-checks the generated client with tsc --strict, and calls the running server from
Bun:
cd e2e && bun install && bun run test§Minimum supported Rust version
Rust 1.88. The repository pins the toolchain used for development and CI in
rust-toolchain.toml; CI also checks the library on 1.88.
§License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Re-exports§
pub use jsonwebtoken;
Modules§
Structs§
- ApiRouter
- Auth
- Body
- Cookies
- Created
- Detail
- DocContext
- Event
Stream - File
- Headers
- JwtKeys
- NoContent
- OpenApi
- Params
- Query
- Request
Issue - Request
Rejection - Scalar
Renderer - Socket
- Socket
Connection - Socket
Upgrade - Status
- Swagger
Renderer - Test
Client - Test
Request - Test
Response - Upload