Skip to content

axum-autodocOpenAPI, inferred.

Write plain axum handlers. Get an OpenAPI 3.2 document, validation, auth and a typed TypeScript client, straight from their signatures.

axum-autodoc logo

Your handler is the spec

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.

src/main.rs
rust
#[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(),
        );
    }
}
GET /users/{id} in /openapi/json
yaml
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.

Three routes, zero setup

Call .openapi(..) on the router and these are served next to your API, on the same paths as @elysiajs/openapi.

  • GET/openapiScalar API reference, or Swagger UI
  • GET/openapi/jsonOpenAPI 3.2 document
  • GET/client.tsTyped TypeScript client

One struct. Parsed, checked, documented.

schemars reads #[garde(..)] directly, so the rules you validate with are the rules your clients see.

Request type
rust
#[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),
    })
}
components.schemas.NewUser and a 400
yaml
type: object
required: [name, email]
properties:
  name:
    type: string
    minLength: 1
    maxLength: 50
  email:
    type: string
    format: email
json
{
  "error": "validation",
  "issues": [
    {
      "path": "email",
      "message": "not a valid email: value is missing `@`"
    }
  ]
}

A client that knows every status

Each call returns a union built from the statuses that route can really return. Narrow on status and TypeScript knows the rest.

Router
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)?;
web/api.ts in use
ts
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;

Also in the box

  • Bearer auth

    Auth<C> verifies a JWT and documents bearerAuth and the 401. The response never says why a token was refused.

  • Every status

    axum's own rejections, validation failures and your typed errors all land in the document.

  • Your own extractors

    Implement DocInput or DocError once and every route that uses the type is documented.

  • Off at compile time

    One environment variable leaves the documentation engine out of the binary. Your code compiles unchanged.

Less to write, more in the document

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.

What each crate gives you out of the box for an axum handler
axum-autodocutoipaaide
No per-handler annotation
Validation from the same schema
Every status that can happen
Typed TypeScript client

Ship docs that cannot drift.

One dependency. Plain handlers. A spec, a reference page and a client on the first run.

cargo add axum-autodoc --features garde,jwt

Released under the MIT or Apache-2.0 license.