expression

REST: RFC 9457 problem details in Axum

Problem details give clients a structured error body in addition to the HTTP status. A type URI identifies the category; title summarizes it, detail explains this occurrence, and status in the body agrees with the HTTP status. This synthetic type URI is illustrative and not a deployed documentation endpoint. Standalone synthetic example. Expected stdout (not executed): 422 application/problem+json Invalid quantity Common mistake: Returning HTTP 200 for a failed operation or exposing internal stack traces.

Formal Syntax & Structure

rust syntaxrust
application/problem+json

Working Example

Example Snippetrust
use axum::{Router, Json, body::{Body, to_bytes}, http::{Request, StatusCode}};use serde::{Deserialize, Serialize};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{http::header, response::IntoResponse};    let response = (StatusCode::UNPROCESSABLE_ENTITY,        [(header::CONTENT_TYPE, "application/problem+json")],        Json(serde_json::json!({"type":"https://api.example.invalid/problems/quantity", "title":"Invalid quantity", "status":422, "detail":"Quantity must be positive."}))).into_response();    println!("{} {}", response.status().as_u16(), response.headers()[header::CONTENT_TYPE].to_str().unwrap());    let value: serde_json::Value = serde_json::from_slice(&to_bytes(response.into_body(), 1024).await.unwrap()).unwrap();    println!("{}", value["title"].as_str().unwrap());}
Rust Reference