Quick start
From an empty crate to a documented API in a few minutes.
Install
[dependencies]
axum-autodoc = { version = "0.2", features = ["garde", "jwt"] }
schemars = "1"
garde = { version = "0.23", features = ["derive", "email"] }cargo add axum-autodoc --features garde,jwt
cargo add schemars@1
cargo add garde@0.23 --features derive,emailschemars 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 | yes | #[api] for summaries, descriptions, tags and more |
ts | yes | 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 (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 axum-extra 0.12 types |
Supported: axum 0.8, axum-extra 0.12 behind extra, Rust 1.88 or later, and an OpenAPI 3.2.0 document (3.1 and 3.0 with .openapi_version(..)). See Compatibility.
Describe your types
Derive JsonSchema next to Serialize and Deserialize. Request types also derive Validate.
#[derive(Serialize, JsonSchema)]
struct User {
id: u32,
name: String,
nickname: Option<String>,
}
#[derive(Deserialize, Validate, JsonSchema)]
struct NewUser {
#[garde(length(min = 1, max = 50))]
name: String,
#[garde(email)]
email: String,
}Write handlers
Handlers are plain async functions. #[api] is optional and only adds what cannot be inferred.
#[api(tag = "Users", summary = "List users", description = "Newest first")]
async fn list_users() -> Json<Vec<User>> {
Json(Vec::new())
}
#[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),
})
}Build the router
ApiRouter has the same shape as axum::Router, plus .openapi(..) and Elysia-style group.
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)?;
let listener = tokio::net::TcpListener::bind("127.0.0.1:3001").await?;
axum::serve(listener, app).await?;openapi() returns the configuration. A minimal one is just a title and version; see Documentation page for everything else.
fn openapi() -> OpenApi {
OpenApi::new()
.title("User API")
.version("1.2.0")
}Open the docs
Run the server and open http://localhost:3001/openapi. The raw document is at /openapi/json and the TypeScript client at /client.ts.
Finishing the router
| Method | Returns | When to use |
|---|---|---|
finish(state) | axum::Router | A failed TypeScript export is printed to stderr and the server keeps going. |
try_finish(state) | Result<Router, error::FinishError> | The build should stop on that error. |
document() | openapi::Document | You only need the document, for a test or a CLI. |
typescript_client(&document) renders the client from a document you already have.
A complete service
examples/users is a full hexagonal 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/openapi