Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Echo GET - accepting Query params

Show how to accept parameters in a GET request.

Dependencies

In addition to the dependencies already used in the earlier example we’ll also need to use serde for serialization.

Pages

There are two function handling two paths:

The main page is static HTML

The rust code is the same as in previous example, but this time the HTML is a bit more complex. The browser will display a form with an entry box and a button that says “Echo”.

async fn main_page() -> Html<&'static str> {
    Html(
        r#"
    <form method="get" action="/echo">
    <input type="text" name="text">
    <input type="submit" value="Echo">
    </form>
    "#,
    )
}

Clicking on that button after typing in the text “Hello World” will bring the browser to a url: /echo?text=Hello+World. (The space was replaced by a + sign.)

We need to create a struct representing the parameters of this query:

Struct describing the parameters

#![allow(unused)]
fn main() {
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Params {
    text: String,
}
}

The echo page is dynamic String

A function that accepts a Params struct wrapped in a Query struct. The variable params will be the deserialized value from the Query string. We can use it to create the string we are returning. We are now returning a String and not a static str because we need to create the string on the fly.

#![allow(unused)]
fn main() {
async fn echo(Query(params): Query<Params>) -> Html<String> {
    println!("params: {:?}", params);
    Html(format!(r#"You said: <b>{}</b>"#, params.text))
}
}

Mapping the routes to functions

Then we map the two pathes to the appropriate functions:

#![allow(unused)]
fn main() {
fn create_router() -> Router {
    Router::new()
        .route("/", get(main_page))
        .route("/echo", get(echo))
}
}

Running

$ cargo run

GET the main page using curl

$ curl http://localhost:3000/

HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
content-length: 131
date: Tue, 18 Mar 2025 08:04:53 GMT


    <form method="get" action="/echo">
    <input type="text" name="text">
    <input type="submit" value="Echo">
    </form>

GET request with parameter

$ curl -i http://localhost:3000/echo?text=Hello+World!

HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
content-length: 29
date: Tue, 18 Mar 2025 08:06:31 GMT

You said: <b>Hello World!</b>

GET request without the parameter

$ curl -i http://localhost:3000/echo

HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
content-length: 56
date: Tue, 18 Mar 2025 08:05:13 GMT

Failed to deserialize query string: missing field `text`

GET request with parameter name but without value

$ curl -i http://localhost:3000/echo?text=
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
content-length: 17
date: Tue, 18 Mar 2025 08:07:04 GMT

You said: <b></b>

Cargo.toml

[package]
name = "echo-get"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]
axum = "0.8.8"
serde = { version = "1.0.228", features = ["derive"] }
tokio = { version = "1.50.0", features = ["full"] }

[dev-dependencies]
headers = "0.4.1"
http-body-util = "0.1.3"
tower = { version = "0.5.3", features = ["util"] }

The full example

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

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Params {
    text: String,
}

async fn main_page() -> Html<&'static str> {
    Html(
        r#"
    <form method="get" action="/echo">
    <input type="text" name="text">
    <input type="submit" value="Echo">
    </form>
    "#,
    )
}

async fn echo(Query(params): Query<Params>) -> Html<String> {
    println!("params: {:?}", params);
    Html(format!(r#"You said: <b>{}</b>"#, params.text))
}

fn create_router() -> Router {
    Router::new()
        .route("/", get(main_page))
        .route("/echo", get(echo))
}

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, create_router()).await.unwrap();
}

#[cfg(test)]
mod tests;

Testing

#![allow(unused)]
fn main() {
use axum::{body::Body, http::Request, http::StatusCode};
use http_body_util::BodyExt;
use tower::ServiceExt;

use super::*;

#[tokio::test]
async fn test_main_page() {
    let response = create_router()
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = response.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let html = String::from_utf8(bytes.to_vec()).unwrap();

    assert!(html.contains(r#"<form method="get" action="/echo">"#));
}

#[tokio::test]
async fn test_echo_with_data() {
    let response = create_router()
        .oneshot(
            Request::builder()
                .uri("/echo?text=Hello+World!")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = response.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let html = String::from_utf8(bytes.to_vec()).unwrap();

    assert_eq!(html, "You said: <b>Hello World!</b>");
}

#[tokio::test]
async fn test_echo_without_data() {
    let response = create_router()
        .oneshot(Request::builder().uri("/echo").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::BAD_REQUEST); // 400
    let body = response.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let html = String::from_utf8(bytes.to_vec()).unwrap();

    assert_eq!(
        html,
        "Failed to deserialize query string: missing field `text`"
    );
}

#[tokio::test]
async fn test_echo_missing_value() {
    let response = create_router()
        .oneshot(
            Request::builder()
                .uri("/echo?text=")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = response.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let html = String::from_utf8(bytes.to_vec()).unwrap();

    assert_eq!(html, "You said: <b></b>");
}

#[tokio::test]
async fn test_echo_extra_param() {
    let response = create_router()
        .oneshot(
            Request::builder()
                .uri("/echo?text=Hello&extra=123")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = response.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let html = String::from_utf8(bytes.to_vec()).unwrap();

    assert_eq!(html, "You said: <b>Hello</b>");
}
}