JSON error body
Learn the exact JSON error body shape an Axum app returns, how axum Json and serde_json json build it, and what the client receives
The JSON error body is the text the client actually receives when a handler fails. For this app it has exactly one shape, an object with a single key called error and a human readable message as its value: {"error":"resource not found"}. Every variant produces it, every handler produces it, and no failure produces anything else. One shape, one key, one message, for the whole app.
Where This Fits
The page about status code mapping explained the number in the status line. This page explains the bytes in the body. The status tells the client what kind of failure happened, and the body tells it in words. The two are decided together in the same implementation, one arm per variant, and this page takes the body half of that arm and follows it from the json! macro to the bytes on the wire.
Think of a letter and its envelope. The status code is the stamp on the outside, which the post office reads to route it. The body is the letter inside, which the recipient reads to understand it. A letter with the right stamp and no content inside is useless, and a letter with content but the wrong stamp goes to the wrong place. The status and the body each do one job, and this page is about the letter.
The Smallest Working Version
The body is built in one line inside the implementation, and it helps to see that line on its own before the rest of the conversion crowds it out.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
AppError::InternalError => (
StatusCode::INTERNAL_SERVER_ERROR,
"something went wrong".to_string(),
),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
The line that builds the body is the last one:
(status, Json(json!({ "error": message }))).into_response()
Three pieces work together in it. json!({ "error": message }) builds a JSON value, an object with one key. Json(...) wraps that value and marks it as a JSON response body. The tuple (status, Json(...)) pairs the status code with the body, and .into_response() turns the pair into a finished Response. The client receives the status line, a content-type: application/json header, and the body bytes {"error":"..."}.
Use it with the three handlers from the earlier pages:
pub mod errors;
use axum::{
Json,
extract::Path,
routing::{get, post},
Router,
};
use errors::AppError;
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
pub struct Book {
pub id: u32,
pub title: String,
}
#[derive(Deserialize)]
pub struct NewBook {
pub title: String,
}
pub fn app() -> Router {
Router::new()
.route("/books/{id}", get(get_book))
.route("/books", post(create_book))
.route("/boom", get(boom))
}
async fn get_book(Path(id): Path<u32>) -> Result<Json<Book>, AppError> {
if id == 1 {
Ok(Json(Book {
id: 1,
title: "The Rust Book".to_string(),
}))
} else {
Err(AppError::NotFound)
}
}
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
if input.title.trim().is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
Ok(Json(Book {
id: 2,
title: input.title,
}))
}
async fn boom() -> Result<&'static str, AppError> {
Err(AppError::InternalError)
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The Cargo.toml file is the same project file as the enum page, with axum, tokio, serde, and serde_json as dependencies and tower as a dev-dependency for tests.
Start the server and ask for the missing book with curl, showing the headers with -i:
curl -i http://127.0.0.1:3000/books/99
The full response is four parts, and each one is worth reading:
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 30
{"error":"resource not found"}
The status line says 404. The content-type header says application/json, which tells the client to parse the body as JSON. The content-length header says 30, which is the exact byte count of the body. The body itself is the JSON object with one key. Nothing else travels: no HTML, no stack trace, no extra fields.
Working Setup:
If curl shows content-type: application/json and the body {"error":"resource not found"}, the body shape is wired up end to end.
Understanding the Body Line Piece by Piece
The body line has three pieces, and each one is a separate library doing one job.
The json! macro
json!({ "error": message })
json! is a macro from the serde_json crate, and it builds a JSON value from a literal shape. The { "error": message } part looks like a Rust struct literal, but it is JSON syntax inside the macro: an object with the key "error" and the value taken from the message variable. The result is a serde_json::Value, a type that can hold any JSON value: an object, an array, a string, a number, or a boolean. Here it always holds an object with one key.
The macro handles the escaping. If the message contains a quote, a backslash, or a newline, the macro escapes it correctly when the value is serialised, so the body stays valid JSON no matter what the message says. A message built by string concatenation would need that escaping done by hand, and hand-done escaping is where broken JSON comes from. The macro removes the whole problem.
The Json wrapper
Json(json!({ "error": message }))
Json is Axum's responder for JSON. Wrapping a value in Json does two things when the response is built: it serialises the value into bytes, and it sets the content-type header to application/json. Without the wrapper, the value would have no way to become a response body with the right header. The wrapper is also what makes the tuple form work, because Axum implements IntoResponse for (StatusCode, Json<T>) where T can be serialised, and a serde_json::Value always can be.
The tuple and into_response
(status, Json(json!({ "error": message }))).into_response()
The tuple pairs the status with the body, and .into_response() converts the pair into a Response. This is the same tuple form the official Axum docs use for building responses with a status and a body, and it is the idiomatic shape for this job. The call consumes the tuple and returns the finished response, with the status from the first element, the serialised JSON as the body from the second, and the content type set by the Json wrapper.
The Concept Behind One Body Shape
A client that consumes an API writes one error parser, and that parser expects one shape. If every failure returns {"error":"..."}, the parser is three lines long: read the body as JSON, take the error key, show it or log it. If one route returns {"error":"..."}, another returns {"message":"..."}, and a third returns plain text, the parser needs a branch per route, and a new route means a new branch. Consistency in the body shape is what keeps client code small.
The single key is a deliberate choice, not a limitation. One key carries the one piece of information every failure needs, a human readable message. More keys would invite inconsistency, because each new key is a decision every handler must make the same way. A richer shape with one message per field exists for a different problem, field-level validation, and it uses the key fields alongside error, as the shared contract for this app states. That shape belongs to its own page. This page's shape is the single-key body, and it stays single-key for every failure it covers.
One Key Means One Parser:
The shape is a contract with every client, not a detail of the server. A client written against {"error":"..."} keeps working as the app grows, because new failures use the same shape. Changing the shape later is a breaking change for every client, so the shape is decided once, here, and kept.
What the Client Actually Receives
It helps to see the same failure through the client's eyes, in three forms: the raw bytes, the parsed JSON, and the values a program would read out of it.
The raw bytes for a missing book are exactly 30 bytes long:
{"error":"resource not found"}
There are no spaces after the colon or the comma, because serde_json serialises objects compactly by default. The byte count in the content-length header, 30, matches that text exactly. A client that reads the body as text sees this string. A client that parses it as JSON sees an object with one key.
Parsed as JSON, the body is:
{
"error": "resource not found"
}
A program reading the parsed object takes the value of the error key and gets the string "resource not found". In a language like JavaScript, that is body.error. In Python, it is body["error"]. In Rust, it is a field on a deserialised struct. The key is always error, the value is always a string, and the string is always the message the implementation chose for that variant.
The three variants produce three bodies, and the table below shows them side by side:
| Variant | Status | Body |
|---|---|---|
NotFound | 404 | {"error":"resource not found"} |
ValidationError("title must not be empty") | 422 | {"error":"title must not be empty"} |
InternalError | 500 | {"error":"something went wrong"} |
The shape never changes. Only the status and the message change, and the message for the validation variant is the only one that varies per request, because it carries the words the handler wrote.
Parsing the Body in a Client
A client that receives the error body usually parses it back into a typed value instead of reading the raw text. In Rust, that means a small struct with one field and a call to serde_json::from_str.
use serde::Deserialize;
#[derive(Deserialize, Debug, PartialEq)]
struct ClientError {
error: String,
}
let parsed: ClientError = serde_json::from_str(r#"{"error":"resource not found"}"#).unwrap();
assert_eq!(parsed.error, "resource not found");
#[derive(Deserialize)] asks serde to write the code that fills the struct from JSON. The field name error matches the JSON key, so the value lands in the field, and parsed.error reads it back as a plain String. The r#"..."# raw string lets the JSON sit in the code with its quotes intact. This round trip, struct to JSON on the server and JSON to struct on the client, is the same ErrorBody shape from the struct section above, read in the opposite direction, and a scratch test asserted that the parse produces exactly the message that was sent.
In other languages the parse is shorter but the idea is the same. A JavaScript client writes await response.json() and reads body.error. A Python client writes response.json()["error"]. Every client reads the same key, because the server writes the same key, and the parse is one line in each language because the shape has only one field to read.
Building the Same Body With a Struct
The json! macro is the quick way to build the body, and a small struct is the typed way. Both produce identical bytes, and the choice between them is about reuse, not about output.
use axum::Json;
use serde::Serialize;
#[derive(Serialize)]
struct ErrorBody {
error: String,
}
let body = Json(ErrorBody {
error: "resource not found".to_string(),
});
#[derive(Serialize)] asks serde to write the code that turns the struct into JSON. The field name error becomes the JSON key, and the field value becomes the JSON value, so the serialised form is {"error":"resource not found"}, byte for byte the same as the macro form. A scratch test asserted that both forms produce the identical string for the same message, and it passed.
Use the macro form when the body is built in one place and never reused, which is the case in this implementation. Use the struct form when the body is built in several places, or when a test or a client deserialises it back into a typed value, because a struct gives the shape a name that the compiler can check. For this app, where the body is built exactly once, the macro form is the better fit, and the struct form is worth knowing for the day the body is built twice.
Reading the Body Back in a Test
A test that reads the body needs to handle the fact that a response body is a stream of bytes, not a string. axum::body::to_bytes collects the stream into one chunk, and String::from_utf8 turns the chunk into text.
async fn body_text(response: axum::response::Response) -> String {
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
String::from_utf8(bytes.to_vec()).unwrap()
}
response.into_body() takes the body out of the response, to_bytes reads it fully, and usize::MAX is the size limit, which means no practical limit for a body this small. The await is needed because reading is asynchronous. The helper is shared by the tests on this page, and it is the same helper the earlier pages used, because reading a body is the same operation no matter which failure produced it.
How the Body Flows
The diagram below follows one validation failure from the message in the variant to the bytes the client reads.
Handler returns Err(ValidationError("title must not be empty"))
|
v
match binds the message from the variant
|
v
json! builds {"error":"title must not be empty"}
|
v
Json wrapper marks it as a JSON body
|
v
Tuple adds status 422, into_response finishes it
|
v
Client reads content-type application/json and the body bytes
The message is written once, in the handler, and it is never copied, reworded, or wrapped in another structure along the way. The json! macro is the only transformation it undergoes, and that transformation only adds the key and the escaping.
Testing the Body
The tests assert the exact body text for all three variants, through the router, and they check the content type header as well.
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn body_text(response: axum::response::Response) -> String {
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[tokio::test]
async fn missing_book_body_is_exactly_one_error_key() {
let response = app()
.oneshot(
Request::builder()
.uri("/books/99")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_eq!(response.headers()["content-type"], "application/json");
assert_eq!(
body_text(response).await,
r#"{"error":"resource not found"}"#
);
}
#[tokio::test]
async fn validation_body_carries_the_handler_message() {
let response = app()
.oneshot(
Request::builder()
.uri("/books")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(r#"{"title":""}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(
body_text(response).await,
r#"{"error":"title must not be empty"}"#
);
}
#[tokio::test]
async fn internal_body_is_the_generic_message() {
let response = app()
.oneshot(
Request::builder()
.uri("/boom")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(
body_text(response).await,
r#"{"error":"something went wrong"}"#
);
}
Each test asserts the full body string, not just a substring, so a change to the key name, an added field, or a reworded message breaks a test. That strictness is deliberate: the body is a contract, and a contract test should fail when the contract changes. All three tests passed against the scratch project, and the live server returned the same bodies through curl. Run them with cargo test and expect:
test missing_book_body_is_exactly_one_error_key ... ok
test validation_body_carries_the_handler_message ... ok
test internal_body_is_the_generic_message ... ok
The r#"..."# syntax is a raw string, which lets the test write the JSON with its quotes inside without escaping them. The response.headers()["content-type"] indexing reads the header value, and the assertion compares it to the exact string "application/json", which is the value the Json wrapper sets.
Common Beginner Mistakes
Returning a plain string instead of JSON
// Wrong - the client gets text/plain, not JSON
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(StatusCode::NOT_FOUND, "resource not found").into_response()
}
}
The tuple (StatusCode, &str) is a valid Axum response, and it sets the content type to text/plain. A client that parses the body as JSON fails on it, because resource not found is not JSON. The fix is the Json(json!({ "error": message })) wrapper, which sets the content type and the body together. The status line looks identical either way, which is why the tests assert the content type header as well as the body.
The Status Line Hides a Wrong Body:
A 404 with a plain-text body looks correct in a curl status line and breaks every JSON client that reads it. Always check the content type header and the body together, in tests and in curl, because the status alone cannot tell you the body is right.
Using a different key per variant
// Wrong - three shapes where the client expects one
AppError::NotFound => (StatusCode::NOT_FOUND, Json(json!({ "message": "resource not found" }))),
AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, Json(json!({ "error": message }))),
AppError::InternalError => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "detail": "something went wrong" }))),
Three keys, message, error, and detail, mean three parsers, and a client that reads the error key finds nothing for the other two variants. The fix is the single-build form from the implementation page, where one json! call builds the body for every variant, so the key cannot differ between arms. One construction site, one key, one shape.
Building the JSON by hand with format!
// Wrong - quotes and backslashes in the message break the body
let body = format!("{{\"error\":\"{}\"}}", message);
A message containing a quote, like title must not contain "quotes", would produce invalid JSON, because the quote inside the message closes the string early. A message with a backslash or a newline breaks it in other ways. The json! macro escapes all of these correctly, because serialisation is its job. Never build JSON with string formatting when a serialiser is available.
Hand-Built JSON Breaks on Real Input:
Messages written by developers rarely contain quotes, and messages built from user input often do. The bug from hand-built JSON only appears when a real user sends a value the developer never tested, which is exactly when it is hardest to debug.
Adding extra fields to one variant
// Wrong - the shape now differs per variant
AppError::NotFound => (StatusCode::NOT_FOUND, Json(json!({
"error": "resource not found",
"id": 99
}))),
An extra field for one variant breaks the single-shape contract, and it leaks a design question into every client: does the id field exist for other variants, and what does its absence mean. If a client genuinely needs the id, it already has it, because it put the id in the URL. Keep the body to the one key, and keep any extra information in the log or in a richer shape designed for that purpose.
Final Complete Example
Here is everything from this page in one place: the enum, the implementation that builds the body, the three handlers, and the tests that pin the body text down.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
AppError::InternalError => (
StatusCode::INTERNAL_SERVER_ERROR,
"something went wrong".to_string(),
),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
pub mod errors;
use axum::{
Json,
extract::Path,
routing::{get, post},
Router,
};
use errors::AppError;
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
pub struct Book {
pub id: u32,
pub title: String,
}
#[derive(Deserialize)]
pub struct NewBook {
pub title: String,
}
pub fn app() -> Router {
Router::new()
.route("/books/{id}", get(get_book))
.route("/books", post(create_book))
.route("/boom", get(boom))
}
async fn get_book(Path(id): Path<u32>) -> Result<Json<Book>, AppError> {
if id == 1 {
Ok(Json(Book {
id: 1,
title: "The Rust Book".to_string(),
}))
} else {
Err(AppError::NotFound)
}
}
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
if input.title.trim().is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
Ok(Json(Book {
id: 2,
title: input.title,
}))
}
async fn boom() -> Result<&'static str, AppError> {
Err(AppError::InternalError)
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run the server, ask for /books/99, and the response is a 404 with content-type: application/json and the body {"error":"resource not found"}. Run cargo test, and the three body tests pass.
Summary
The body is the smallest contract in the app, and its smallness is its strength. One key, one string, one content type, for every failure, decided in one line of one implementation. The decision framework for any future change to it is a single question: does every client still parse it with the same three lines. When the answer is yes, the change is safe. When the answer is no, the change is a breaking change, and it needs the same care as a renamed route or a removed field. The insight that ties the status and the body together is that they answer different questions for different readers. The status answers the machine's question, what kind of failure is this and what should I do. The body answers the human's question, what went wrong in words I can read. A good error response answers both, in the same breath, and this shape does exactly that.