Echo POST
Show how to accept parameters in a POST request.
Running
cargo run
GET the main page
$ curl -i http://localhost:3000/
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
content-length: 132
date: Tue, 18 Mar 2025 08:21:36 GMT
<form method="post" action="/echo">
<input type="text" name="text">
<input type="submit" value="Echo">
</form>
POST request setting the header and the data
$ curl -i -X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
--data "text=Hello World!" \
http://localhost:3000/echo
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
content-length: 29
date: Tue, 18 Mar 2025 08:23:51 GMT
You said: <b>Hello World!</b>
POST missing parameter
$ curl -i -X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
http://localhost:3000/echo
HTTP/1.1 422 Unprocessable Entity
content-type: text/plain; charset=utf-8
content-length: 53
date: Tue, 18 Mar 2025 08:25:39 GMT
Failed to deserialize form body: missing field `text`
[package]
name = "echo-post"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
axum = "0.8.8"
mime = "0.3.17"
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 code
use axum::{
response::Html,
routing::{get, post},
Form, 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="post" action="/echo">
<input type="text" name="text">
<input type="submit" value="Echo">
</form>
"#,
)
}
async fn echo(Form(params): Form<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", post(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 super::*;
use axum::{
body::Body,
http::{self, Request, StatusCode},
};
use http_body_util::BodyExt;
use tower::ServiceExt;
#[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="post" action="/echo">"#));
}
#[tokio::test]
async fn test_echo_with_data() {
let response = create_router()
.oneshot(
Request::builder()
.method(http::Method::POST)
.uri("/echo")
.header(
http::header::CONTENT_TYPE,
mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
)
.body(Body::from("text=Hello+World!"))
.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()
.method(http::Method::POST)
.uri("/echo")
.header(
http::header::CONTENT_TYPE,
mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); // 422
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 form body: missing field `text`"
);
}
#[tokio::test]
async fn test_echo_missing_value() {
let response = create_router()
.oneshot(
Request::builder()
.method(http::Method::POST)
.uri("/echo")
.header(
http::header::CONTENT_TYPE,
mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
)
.body(Body::from("text="))
.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()
.method(http::Method::POST)
.uri("/echo")
.header(
http::header::CONTENT_TYPE,
mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
)
.body(Body::from("text=Hello&extra=123"))
.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>");
}
}