Skip to main content

Crate axum_typed_routing

Crate axum_typed_routing 

Source
Expand description

§Basic usage

The following example demonstrates the basic usage of the library. On top of any regular handler, you can add the route macro to create a typed route. Any path- or query-parameters in the url will be type-checked at compile-time, and properly extracted into the handler.

The following example shows how the path parameter id, and query parameters amount and offset are type-checked and extracted into the handler.

#![allow(unused)]
use axum::extract::{Json, State};
use axum_typed_routing::{TypedRouter, route};

#[route(GET "/item/{id}?amount&offset")]
async fn item_handler(
    id: u32,
    amount: Option<u32>,
    offset: Option<u32>,
    State(state): State<String>,
    Json(json): Json<u32>,
) -> String {
    todo!("handle request")
}

fn main() {
    let router: axum::Router = axum::Router::new()
        .typed_route(item_handler)
        .with_state("state".to_string());
}

Some valid url’s as get-methods are:

  • /item/1?amount=2&offset=3
  • /item/1?amount=2
  • /item/1?offset=3
  • /item/500

By marking the amount and offset parameters as Option<T>, they become optional.

§Example with aide

When the aide feature is enabled, it’s possible to automatically generate OpenAPI documentation for the routes. The api_route macro is used in place of the route macro.

Please read the aide documentation for more information on usage.

#![allow(unused)]
use aide::{OperationInput, axum::ApiRouter};
use axum::extract::{Json, State};
use axum_typed_routing::TypedApiRouter;
use axum_typed_routing_macros::api_route;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[api_route(debug GET "/item/{id}?amount&offset" {
    summary: "Get an item",
    description: "Get an item by id",
    id: "get-item",
    tags: ["items"],
    hidden: false,
})]
async fn item_handler(
    /// The id of the item to get
    id: u32,
    /// The amount of items to get
    amount: Option<u32>,
    /// The offset of the items to get
    offset: Option<u32>,
    State(state): State<String>,
    json: String,
) -> String {
    todo!("handle request")
}

fn main() {
    let router: ApiRouter = ApiRouter::new()
        .typed_api_route(item_handler)
        .with_state("state".to_string());
}

#[derive(Serialize, Deserialize, JsonSchema)]
pub struct Integer(pub u32);

impl OperationInput for Integer {}

Traits§

TypedApiRouter
Same as TypedRouter, but with support for aide.
TypedRouter
A trait that allows typed routes, created with the route macro to be added to an axum router.

Attribute Macros§

api_route
Same as route, but with support for OpenApi using aide. See route for more information and examples.
route
A macro that generates statically-typed routes for axum handlers.