axum-api-kit 1.3.0

Shared response types for Axum JSON APIs: ApiError, ListResponse, and HealthResponse
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! RFC 9457 `application/problem+json` error responses.
//!
//! [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) (Problem Details for HTTP
//! APIs) defines a standard JSON error shape - `type`, `title`, `status`,
//! `detail`, `instance`, plus arbitrary extension members - served with the
//! `application/problem+json` media type. [`Problem`] implements that shape as
//! a chainable builder that converts into an Axum response.
//!
//! # `Problem` vs [`ApiError`](crate::ApiError)
//!
//! [`ApiError`](crate::ApiError)'s flat `{ code, message, details }` body is
//! the kit's default and remains the right choice for services that own both
//! ends of the wire. Reach for `Problem` when the error format needs to
//! interoperate: API gateways that understand problem+json, OpenAPI tooling
//! that expects the RFC 9457 members, or polyglot clients standardizing on the
//! RFC across services.
//!
//! A separate type exists because `ApiError`'s serialization and factory
//! tuples are frozen under the 1.x stability promise, and `axum::Json` can
//! only emit `Content-Type: application/json`; `Problem` builds its own
//! response so it can send `application/problem+json`. The `From` impls in
//! this module bridge an existing `ApiError` (or a factory tuple) into a
//! `Problem` losslessly.
//!
//! # Out of scope for this release
//!
//! - Accept-header content negotiation middleware (choosing `application/json`
//!   or `application/problem+json` based on the request).
//! - A problem+json rejection mode for `ValidatedJson` / `ApiJson`.
//! - HTTP-date `Retry-After` values (only delay-seconds are emitted).
//!
//! All three are candidates for a future minor release.

use axum::{
    http::{header, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    Json,
};
use serde::Serialize;

use crate::ApiError;

/// The `application/problem+json` media type from RFC 9457.
///
/// # Example
///
/// ```rust
/// use axum_api_kit::APPLICATION_PROBLEM_JSON;
///
/// assert_eq!(APPLICATION_PROBLEM_JSON, "application/problem+json");
/// ```
pub const APPLICATION_PROBLEM_JSON: &str = "application/problem+json";

/// An RFC 9457 problem details response body.
///
/// Serializes as:
/// ```json
/// { "title": "Not Found", "status": 404 }
/// { "type": "https://example.com/probs/out-of-credit", "title": "Insufficient credit",
///   "status": 403, "detail": "Balance is 30, item costs 50",
///   "instance": "/account/12345/msgs/abc", "balance": 30 }
/// ```
///
/// Implements [`IntoResponse`] with `Content-Type: application/problem+json`
/// and an optional delay-seconds `Retry-After` header.
///
/// # Example
///
/// ```rust
/// use axum::{http::StatusCode, response::IntoResponse};
/// use axum_api_kit::Problem;
///
/// async fn handler() -> impl IntoResponse {
///     Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
///         .with_type("https://example.com/probs/out-of-credit")
///         .with_detail("Balance is 30, item costs 50")
///         .with_instance("/account/12345/msgs/abc")
///         .with_extension("balance", 30)
/// }
/// ```
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct Problem {
    /// A URI reference identifying the problem type. Absent means "about:blank" per RFC 9457.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub type_uri: Option<String>,
    /// A short, human-readable summary of the problem type. Stable per problem type.
    pub title: String,
    /// The HTTP status code, duplicated in the body per RFC 9457.
    pub status: u16,
    /// A human-readable explanation specific to this occurrence.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    /// A URI reference identifying this specific occurrence.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance: Option<String>,
    /// RFC 9457 extension members, flattened to top-level JSON keys.
    #[serde(flatten)]
    #[cfg_attr(feature = "openapi", schema(value_type = Object))]
    pub extensions: serde_json::Map<String, serde_json::Value>,
    /// Optional Retry-After header delay. Header-only; never serialized in the body.
    #[serde(skip)]
    #[cfg_attr(feature = "openapi", schema(ignore))]
    pub retry_after: Option<std::time::Duration>,
}

impl Problem {
    /// Builds a minimal `Problem` with the given status and title.
    ///
    /// `type`, `detail`, and `instance` start absent, extensions start empty,
    /// and no `Retry-After` header is emitted.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::NOT_FOUND, "Not Found");
    /// assert_eq!(
    ///     serde_json::to_value(&problem).unwrap(),
    ///     serde_json::json!({ "title": "Not Found", "status": 404 })
    /// );
    /// ```
    pub fn new(status: StatusCode, title: impl Into<String>) -> Self {
        Self {
            type_uri: None,
            title: title.into(),
            status: status.as_u16(),
            detail: None,
            instance: None,
            extensions: serde_json::Map::new(),
            retry_after: None,
        }
    }

    /// Sets the `type` member: a URI reference identifying the problem type.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
    ///     .with_type("https://example.com/probs/out-of-credit");
    /// let v = serde_json::to_value(&problem).unwrap();
    /// assert_eq!(v["type"], "https://example.com/probs/out-of-credit");
    /// ```
    pub fn with_type(mut self, type_uri: impl Into<String>) -> Self {
        self.type_uri = Some(type_uri.into());
        self
    }

    /// Sets the `detail` member: a human-readable explanation specific to this
    /// occurrence.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
    ///     .with_detail("Balance is 30, item costs 50");
    /// let v = serde_json::to_value(&problem).unwrap();
    /// assert_eq!(v["detail"], "Balance is 30, item costs 50");
    /// ```
    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    /// Sets the `instance` member: a URI reference identifying this specific
    /// occurrence.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
    ///     .with_instance("/account/12345/msgs/abc");
    /// let v = serde_json::to_value(&problem).unwrap();
    /// assert_eq!(v["instance"], "/account/12345/msgs/abc");
    /// ```
    pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
        self.instance = Some(instance.into());
        self
    }

    /// Adds an RFC 9457 extension member, serialized as a top-level JSON key.
    ///
    /// If `key` is one of the reserved members (`"type"`, `"title"`,
    /// `"status"`, `"detail"`, `"instance"`), the call is a silent no-op so
    /// the flattened extensions can never emit duplicate JSON keys. This
    /// mirrors the [`ApiError::with_source`] silent-no-op precedent.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
    ///     .with_extension("balance", 30)
    ///     .with_extension("status", 999); // reserved key: ignored
    /// let v = serde_json::to_value(&problem).unwrap();
    /// assert_eq!(v["balance"], 30);
    /// assert_eq!(v["status"], 403);
    /// ```
    pub fn with_extension(
        mut self,
        key: impl Into<String>,
        value: impl Into<serde_json::Value>,
    ) -> Self {
        let key = key.into();
        if matches!(
            key.as_str(),
            "type" | "title" | "status" | "detail" | "instance"
        ) {
            return self;
        }
        self.extensions.insert(key, value.into());
        self
    }

    /// Emits a delay-seconds `Retry-After` header on the response, rounded up
    /// to whole seconds (1500ms becomes `"2"`).
    ///
    /// The delay never appears in the JSON body; add it via
    /// [`with_extension`](Self::with_extension) if body presence is wanted.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::{http::StatusCode, response::IntoResponse};
    /// use axum_api_kit::Problem;
    /// use std::time::Duration;
    ///
    /// let res = Problem::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests")
    ///     .with_retry_after(Duration::from_secs(30))
    ///     .into_response();
    /// assert_eq!(res.headers().get("retry-after").unwrap(), "30");
    /// ```
    pub fn with_retry_after(mut self, delay: std::time::Duration) -> Self {
        self.retry_after = Some(delay);
        self
    }

    /// Returns the `status` field as a [`StatusCode`], falling back to
    /// `500 Internal Server Error` when it is not a valid status.
    ///
    /// `StatusCode::from_u16` accepts `100..=999`, so the fallback only
    /// triggers for a hand-set `pub status` outside that range.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::NOT_FOUND, "Not Found");
    /// assert_eq!(problem.status_code(), StatusCode::NOT_FOUND);
    /// ```
    pub fn status_code(&self) -> StatusCode {
        StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
    }
}

impl IntoResponse for Problem {
    fn into_response(self) -> Response {
        // axum::Json hardcodes Content-Type: application/json, so the response
        // is built via the (StatusCode, [(HeaderName, HeaderValue); 1], Vec<u8>)
        // tuple instead; the header part's insert overrides the
        // application/octet-stream default that Vec<u8> alone would set. The
        // same tuple pattern is used by Created::with_location in success.rs.
        // On the practically unreachable serialization failure, both the status
        // line and the body say 500 so they stay consistent.
        let retry = self.retry_after;
        let (status, body) = match serde_json::to_vec(&self) {
            Ok(bytes) => (self.status_code(), bytes),
            Err(_) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                br#"{"title":"Internal Server Error","status":500}"#.to_vec(),
            ),
        };
        let mut res = (
            status,
            [(
                header::CONTENT_TYPE,
                HeaderValue::from_static(APPLICATION_PROBLEM_JSON),
            )],
            body,
        )
            .into_response();
        if let Some(d) = retry {
            res.headers_mut().insert(
                header::RETRY_AFTER,
                HeaderValue::from(crate::error::ceil_secs(d)),
            );
        }
        res
    }
}

/// Convert a `(StatusCode, ApiError)` pair into a [`Problem`], losslessly.
///
/// | source | `Problem` member |
/// |---|---|
/// | status | `status` |
/// | status canonical reason | `title` (falls back to `code` for nonstandard statuses; cosmetic) |
/// | `message` | `detail` |
/// | `code` | `"code"` extension member |
/// | `details` (when present) | `"details"` extension member, verbatim |
///
/// `details` is kept under the single `"details"` key, never flattened, so
/// validation field maps cannot collide with reserved members. `type` and
/// `instance` are left absent, and no `Retry-After` header is set.
impl From<(StatusCode, ApiError)> for Problem {
    fn from((status, err): (StatusCode, ApiError)) -> Self {
        let title = status
            .canonical_reason()
            .map(str::to_owned)
            .unwrap_or_else(|| err.code.clone());
        let mut extensions = serde_json::Map::new();
        extensions.insert("code".to_owned(), serde_json::Value::String(err.code));
        if let Some(details) = err.details {
            extensions.insert("details".to_owned(), details);
        }
        Self {
            type_uri: None,
            title,
            status: status.as_u16(),
            detail: Some(err.message),
            instance: None,
            extensions,
            retry_after: None,
        }
    }
}

/// Convert a `(StatusCode, Json<ApiError>)` factory tuple into a [`Problem`].
///
/// Unwraps the [`Json`] and delegates to [`From<(StatusCode, ApiError)>`], so
/// existing factory results convert directly:
/// `Problem::from(ApiError::not_found("nope"))`.
impl From<(StatusCode, Json<ApiError>)> for Problem {
    fn from((status, Json(err)): (StatusCode, Json<ApiError>)) -> Self {
        Problem::from((status, err))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::time::Duration;

    #[test]
    fn minimal_serialization_omits_optional_members() {
        let problem = Problem::new(StatusCode::NOT_FOUND, "Not Found");
        let v = serde_json::to_value(&problem).unwrap();
        assert_eq!(v, json!({ "title": "Not Found", "status": 404 }));
        assert!(v.get("type").is_none());
        assert!(v.get("detail").is_none());
        assert!(v.get("instance").is_none());
    }

    #[test]
    fn full_shape_serializes_all_rfc_members() {
        let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
            .with_type("https://example.com/probs/out-of-credit")
            .with_detail("Balance is 30, item costs 50")
            .with_instance("/account/12345/msgs/abc");
        let v = serde_json::to_value(&problem).unwrap();
        assert_eq!(v["type"], "https://example.com/probs/out-of-credit");
        assert_eq!(v["title"], "Insufficient credit");
        assert_eq!(v["status"], 403);
        assert_eq!(v["detail"], "Balance is 30, item costs 50");
        assert_eq!(v["instance"], "/account/12345/msgs/abc");
        assert!(v.get("type_uri").is_none());
    }

    #[test]
    fn extensions_flatten_to_top_level() {
        let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
            .with_extension("balance", 30);
        let v = serde_json::to_value(&problem).unwrap();
        assert_eq!(v["balance"], 30);
        assert!(v.get("extensions").is_none());
    }

    #[test]
    fn with_extension_ignores_reserved_keys() {
        let problem = Problem::new(StatusCode::NOT_FOUND, "Not Found")
            .with_extension("status", 999)
            .with_extension("type", "https://example.com/overridden")
            .with_extension("title", "Overridden")
            .with_extension("detail", "overridden")
            .with_extension("instance", "/overridden");
        let v = serde_json::to_value(&problem).unwrap();
        assert_eq!(v, json!({ "title": "Not Found", "status": 404 }));
    }

    #[test]
    fn retry_after_never_serialized() {
        let problem = Problem::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests")
            .with_retry_after(Duration::from_secs(30));
        let v = serde_json::to_value(&problem).unwrap();
        assert!(v.get("retry_after").is_none());
    }

    #[tokio::test]
    async fn into_response_status_content_type_body() {
        let res = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
            .with_type("https://example.com/probs/out-of-credit")
            .with_detail("Balance is 30, item costs 50")
            .with_instance("/account/12345/msgs/abc")
            .with_extension("balance", 30)
            .into_response();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
        assert_eq!(
            res.headers().get(header::CONTENT_TYPE).unwrap(),
            APPLICATION_PROBLEM_JSON
        );
        let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            body,
            json!({
                "type": "https://example.com/probs/out-of-credit",
                "title": "Insufficient credit",
                "status": 403,
                "detail": "Balance is 30, item costs 50",
                "instance": "/account/12345/msgs/abc",
                "balance": 30
            })
        );
    }

    #[tokio::test]
    async fn retry_after_header_seconds() {
        let res = Problem::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests")
            .with_retry_after(Duration::from_secs(30))
            .into_response();
        assert_eq!(res.headers().get(header::RETRY_AFTER).unwrap(), "30");

        let res = Problem::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests")
            .with_retry_after(Duration::from_millis(1500))
            .into_response();
        assert_eq!(res.headers().get(header::RETRY_AFTER).unwrap(), "2");
    }

    #[test]
    fn from_status_apierror_maps_fields() {
        let err =
            ApiError::new("NOT_FOUND", "item 42 does not exist").with_details(json!({ "id": 42 }));
        let problem = Problem::from((StatusCode::NOT_FOUND, err));
        assert_eq!(problem.title, "Not Found");
        assert_eq!(problem.status, 404);
        assert_eq!(problem.detail.as_deref(), Some("item 42 does not exist"));
        assert_eq!(problem.extensions["code"], "NOT_FOUND");
        assert_eq!(problem.extensions["details"], json!({ "id": 42 }));

        let no_details = Problem::from((StatusCode::NOT_FOUND, ApiError::new("NOT_FOUND", "nope")));
        assert!(!no_details.extensions.contains_key("details"));
    }

    #[test]
    fn from_status_json_apierror_unwraps() {
        let via_factory = Problem::from(ApiError::not_found("nope"));
        let direct = Problem::from((StatusCode::NOT_FOUND, ApiError::new("NOT_FOUND", "nope")));
        assert_eq!(
            serde_json::to_value(&via_factory).unwrap(),
            serde_json::to_value(&direct).unwrap()
        );
    }

    #[test]
    fn status_code_falls_back_to_500() {
        // StatusCode::from_u16 accepts 100..=999, so use a value below 100.
        let problem = Problem {
            type_uri: None,
            title: "weird".to_owned(),
            status: 42,
            detail: None,
            instance: None,
            extensions: serde_json::Map::new(),
            retry_after: None,
        };
        assert_eq!(problem.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
    }
}