FAQ - Help and questions

How do I accept and return JSON in an axum handler, with the right status codes?

#axum#json#api#serdepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Take Json<T> as the last handler argument to read a request body, and return Json<U> to send one; both need serde derives. Return a tuple (StatusCode::CREATED, Json(..)) to set a status, and Result<Json<T>, StatusCode> when a lookup can fail. The response gets content-type application/json.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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:

text
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.
Cargo.tomltoml
axum = "0.8.9"
serde = { version = "1.0.229", features = ["derive"] }
tokio = { version = "1.54.1", features = ["full"] }

Common mistakes#

  • Putting Json before 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).

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet