expression

Axum: GET and POST on one path

HTTP method routing distinguishes operations on the same resource path. Here GET describes a resource and POST returns a creation status. The POST handler is a demonstration only; it does not persist data. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): GET: 200 POST: 201 PUT: 405 Common mistake: Assuming every method on a recognized path reaches the same handler.

Formal Syntax & Structure

rust syntaxrust
get(read).post(create)

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::routing::get;    let app = Router::new().route("/items", get(|| async { "list" }).post(|| async { StatusCode::CREATED }));    for method in ["GET", "POST", "PUT"] {        let r = app.clone().oneshot(Request::builder().method(method).uri("/items").body(Body::empty()).unwrap()).await.unwrap();        println!("{method}: {}", r.status().as_u16());    }}
Rust Reference