Answer#
Json<T> is both an extractor (for the request body) and a response type. Put it last in the argument list because it consumes the body.
use axum::{
body::{to_bytes, Body},
extract::Path,
http::{header, Request, StatusCode},
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use tower::ServiceExt;
#[derive(Deserialize)]
struct NewTodo { title: String }
#[derive(Serialize)]
struct Todo { id: u32, title: String, done: bool }
async fn create(Json(new): Json<NewTodo>) -> (StatusCode, Json<Todo>) {
(StatusCode::CREATED, Json(Todo { id: 1, title: new.title, done: false }))
}
async fn show(Path(id): Path<u32>) -> Result<Json<Todo>, StatusCode> {
if id == 1 { Ok(Json(Todo { id, title: "write docs".into(), done: false })) } else { Err(StatusCode::NOT_FOUND) }
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/todos", post(create)).route("/todos/{id}", get(show));
let post_json = Request::post("/todos").header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"title":"buy milk"}"#)).unwrap();
for req in [post_json, Request::get("/todos/1").body(Body::empty()).unwrap(), Request::get("/todos/2").body(Body::empty()).unwrap()] {
let res = app.clone().oneshot(req).await.unwrap();
let (status, ctype) = (res.status(), res.headers().get(header::CONTENT_TYPE).cloned());
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{status} {ctype:?} {:?}", String::from_utf8_lossy(&body));
}
}Output:
201 Created Some("application/json") "{\"id\":1,\"title\":\"buy milk\",\"done\":false}"
200 OK Some("application/json") "{\"id\":1,\"title\":\"write docs\",\"done\":false}"
404 Not Found None ""(StatusCode::CREATED, Json(todo))sets status 201 and the JSON body together.Result<Json<Todo>, StatusCode>lets the handler return an error status:Err(StatusCode::NOT_FOUND)gave status 404 with no body and no content type.- The request must carry
Content-Type: application/json; see the thread on 415 and 422 answers for what happens otherwise.
axum = "0.8.9"
serde = { version = "1.0.229", features = ["derive"] }
tokio = { version = "1.54.1", features = ["full"] }Common mistakes#
- Putting
Jsonbefore other extractors; it must be last (see the thread on the extractor order). - Returning a bare 404 with no body to a JSON client. Give errors a body in a consistent shape (see the thread on error responses).
Related questions#
How do I send JSON that is not a struct?#
Json(serde_json::json!({ "ok": true })) works for ad-hoc values, with the serde_json crate.
Can the same handler return JSON or HTML?#
Use two routes, or return impl IntoResponse from one branch each; the thread on templates shows an HTML response.
Sources#
- axum,
Json: https://docs.rs/axum/0.8.9/axum/struct.Json.html (read 2026-12-05) - axum,
IntoResponse: https://docs.rs/axum/0.8.9/axum/response/trait.IntoResponse.html (read 2026-12-05)