Troubleshooting - Help and questions

Why does my axum JSON endpoint answer 415, 400 or 422?

#axum#json#troubleshooting#http-statusasked 0 answers0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

The Json extractor rejects a request before your handler runs. 415 means the Content-Type header is not application/json, 400 means the body is not valid JSON, and 422 means it is valid JSON that does not match the struct (missing field or wrong type). The response text names the cause.

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

Symptom#

A POST to a handler that takes Json<T> returns an error status and your handler is never called. The status tells which check failed.

Cause#

The extractor checks three things in order: the content type, the JSON syntax, and the shape of the data. This program sends five bodies to one handler:

src/main.rsrust
use axum::{body::{to_bytes, Body}, http::{header, Request}, routing::post, Json, Router};
use serde::Deserialize;
use tower::ServiceExt;

#[derive(Deserialize)]
struct NewTodo { title: String }

async fn create(Json(n): Json<NewTodo>) -> String { format!("ok: {}", n.title) }

#[tokio::main]
async fn main() {
    let app = Router::new().route("/todos", post(create));
    let cases: [(&str, Option<&str>, &str); 5] = [
        ("good", Some("application/json"), r#"{"title":"a"}"#),
        ("no content-type", None, r#"{"title":"a"}"#),
        ("broken json", Some("application/json"), r#"{"title":"a""#),
        ("missing field", Some("application/json"), r#"{}"#),
        ("wrong type", Some("application/json"), r#"{"title":5}"#),
    ];
    for (name, ctype, body) in cases {
        let mut b = Request::post("/todos");
        if let Some(c) = ctype { b = b.header(header::CONTENT_TYPE, c); }
        let res = app.clone().oneshot(b.body(Body::from(body)).unwrap()).await.unwrap();
        let status = res.status().as_u16();
        let text = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("{name}: {status} {}", String::from_utf8_lossy(&text));
    }
}
text
good: 200 ok: a
no content-type: 415 Expected request with `Content-Type: application/json`
broken json: 400 Failed to parse the request body as JSON: EOF while parsing an object at line 1 column 12
missing field: 422 Failed to deserialize the JSON body into the target type: missing field `title` at line 1 column 2
wrong type: 422 Failed to deserialize the JSON body into the target type: title: invalid type: integer `5`, expected a string at line 1 column 10
StatusMeaningFix
415no Content-Type: application/json headeradd the header in the client (curl -H "Content-Type: application/json" ...)
400the body is not valid JSON (the text gives line and column)fix the JSON; check for a cut-off body or a trailing comma
422valid JSON, but a field is missing or has the wrong type (the text names it)send the field, or make it Option<T> / #[serde(default)] in the struct

Fix#

Read the response text, not just the status: it quotes serde's message, for example `missing field title `. If browsers or other clients need a JSON error body instead of this plain text, wrap the failures in your own error type (see the thread on error responses).

Common mistakes#

  • Testing with a tool that sends form data and forgetting to switch the body type to JSON.
  • Sending numbers as strings ("5") to a numeric field: that is the 422 "wrong type" case.

Can a field be optional?#

Yes: declare it Option<T> and a missing field becomes None.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No answers yet

    No answers yet. If you know, answer it.