typestar

Path and Query extractors in Rust

Typed extractors pull the parts of a URL apart for you.

use axum::extract::{Path, Query};
use axum::{routing::get, Router};
use serde::Deserialize;

#[derive(Deserialize)]
struct Filter {
    lang: String,
    #[serde(default)]
    min_steps: usize,
}

async fn step(Path((tour, idx)): Path<(String, u32)>) -> String {
    format!("{tour} step {idx}")
}

async fn tours(Query(filter): Query<Filter>) -> String {
    format!("{} with at least {} steps", filter.lang, filter.min_steps)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/tours/{tour}/steps/{idx}", get(step))
        .route("/tours", get(tours));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

How it works

  1. Path destructures the placeholders in the route.
  2. Query deserializes the query string into a struct.
  3. A missing or unparsable value is rejected automatically.

Keywords and builtins used here

The run, in numbers

Lines
29
Characters to type
670
Tokens
191
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 104 seconds.

Type this snippet

Step 1 of 2 in Extractors & state, step 4 of 9 in Web services with axum.

← Previous Next →