Skip to content

Quick start ​

From an empty crate to a documented API in a few minutes.

Install ​

toml
[dependencies]
axum-autodoc = { version = "0.2", features = ["garde", "jwt"] }
schemars = "1"
garde = { version = "0.23", features = ["derive", "email"] }
sh
cargo add axum-autodoc --features garde,jwt
cargo add schemars@1
cargo add garde@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, …).

FeatureDefaultAdds
macrosyes#[api] for summaries, descriptions, tags and more
tsyesTypeScript client at /client.ts and export_ts
gardeBody<T>, Query<T>, Params<T> with validation
jwtAuth<C> bearer extractor and JwtKeys
multipartUpload<T> and File (adds garde)
sseEventStream<T> for server-sent events
wsSocket<In, Out> for typed WebSockets
test-clientApiRouter::test_client for in-memory tests
extradocuments 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.

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

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

rust
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.

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

MethodReturnsWhen to use
finish(state)axum::RouterA 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::DocumentYou 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.

sh
cargo run -p axum-autodoc --example users --all-features
open http://localhost:3000/openapi

Released under the MIT or Apache-2.0 license.