Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Get A URL Query Parameter From A Request In axum

Code

[package]
name = "axum_query_param_test"
version = "0.1.0"
edition = "2021"

[dependencies]
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
axum = "0.6"

Code

use axum::extract::Query;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::{response::Html, Router};
use serde::Deserialize;
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let welcome_route = Router::new().route("/welcome", get(welcome_query_handler));
    let addr = SocketAddr::from(([127, 0, 0, 1], 8181));
    axum::Server::bind(&addr)
        .serve(welcome_route.into_make_service())
        .await
        .unwrap();
}

#[derive(Debug, Deserialize)]
struct WelcomeParams {
    name: Option<String>,
}

async fn welcome_query_handler(Query(params): Query<WelcomeParams>) -> impl IntoResponse {
    println!("Got request for /welcome");
    match params.name {
        Some(name) => Html(format!("Hello, {}", name.as_str())),
        None => Html("Hello, whoever you are".to_string()),
    }
}
  • Update example to pull route into its own function and use route `.merge()`` like: id: 2v5bmyjc

References

  • This is the video I got the base example off of. It did some fancier stuff that I removed to simplify it to make it easier for me to understand.