axum-api-kit 0.9.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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use axum::{http::StatusCode, Json};
use serde::Serialize;
use serde_json::Value;
use std::fmt;

/// A machine-readable JSON error body.
///
/// Serializes as:
/// ```json
/// { "code": "NOT_FOUND", "message": "item not found" }
/// { "code": "VALIDATION_ERROR", "message": "invalid input", "details": { "field": "name" } }
/// ```
///
/// Use the factory methods to get a `(StatusCode, Json<ApiError>)` tuple, which implements
/// [`IntoResponse`] and can be returned directly from Axum handlers.
///
/// # Example
///
/// ```rust
/// use axum::response::IntoResponse;
/// use axum_api_kit::ApiError;
///
/// async fn handler() -> impl IntoResponse {
///     ApiError::not_found("item not found")
/// }
/// ```
#[derive(Debug, Clone, Serialize)]
pub struct ApiError {
    /// A short, stable, machine-readable error identifier. Use `SCREAMING_SNAKE_CASE`.
    pub code: String,
    /// A human-readable description of the error.
    pub message: String,
    /// Optional structured details (field-level validation errors, etc.).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Value>,
}

impl ApiError {
    /// Construct a bare `ApiError` without a bundled status code.
    ///
    /// Prefer the factory methods ([`not_found`](Self::not_found), etc.) when returning
    /// responses directly from handlers.
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            details: None,
        }
    }

    /// Attach structured details to this error.
    pub fn with_details(mut self, details: Value) -> Self {
        self.details = Some(details);
        self
    }

    // --- Factory helpers ---
    // Each returns (StatusCode, Json<ApiError>) which implements IntoResponse.

    /// `400 Bad Request` with the provided `code` and `message`.
    pub fn bad_request(
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> (StatusCode, Json<Self>) {
        (StatusCode::BAD_REQUEST, Json(Self::new(code, message)))
    }

    /// `401 Unauthorized` - `code` defaults to `"AUTH_REQUIRED"`.
    pub fn unauthorized(message: impl Into<String>) -> (StatusCode, Json<Self>) {
        (
            StatusCode::UNAUTHORIZED,
            Json(Self::new("AUTH_REQUIRED", message)),
        )
    }

    /// `403 Forbidden` - `code` defaults to `"FORBIDDEN"`.
    pub fn forbidden(message: impl Into<String>) -> (StatusCode, Json<Self>) {
        (StatusCode::FORBIDDEN, Json(Self::new("FORBIDDEN", message)))
    }

    /// `404 Not Found` - `code` defaults to `"NOT_FOUND"`.
    pub fn not_found(message: impl Into<String>) -> (StatusCode, Json<Self>) {
        (StatusCode::NOT_FOUND, Json(Self::new("NOT_FOUND", message)))
    }

    /// `409 Conflict` - `code` defaults to `"CONFLICT"`.
    pub fn conflict(message: impl Into<String>) -> (StatusCode, Json<Self>) {
        (StatusCode::CONFLICT, Json(Self::new("CONFLICT", message)))
    }

    /// `422 Unprocessable Entity` - `code` defaults to `"VALIDATION_ERROR"`.
    pub fn unprocessable(message: impl Into<String>) -> (StatusCode, Json<Self>) {
        (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(Self::new("VALIDATION_ERROR", message)),
        )
    }

    /// `500 Internal Server Error` - `code` defaults to `"INTERNAL_ERROR"`.
    pub fn internal(message: impl Into<String>) -> (StatusCode, Json<Self>) {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(Self::new("INTERNAL_ERROR", message)),
        )
    }

    /// `500 Internal Server Error` for database failures - `code` is `"DB_ERROR"`.
    pub fn db_error() -> (StatusCode, Json<Self>) {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(Self::new("DB_ERROR", "database error")),
        )
    }

    /// `429 Too Many Requests` - `code` defaults to `"RATE_LIMITED"`.
    pub fn too_many_requests(message: impl Into<String>) -> (StatusCode, Json<Self>) {
        (
            StatusCode::TOO_MANY_REQUESTS,
            Json(Self::new("RATE_LIMITED", message)),
        )
    }

    /// `503 Service Unavailable` - `code` defaults to `"SERVICE_UNAVAILABLE"`.
    pub fn service_unavailable(message: impl Into<String>) -> (StatusCode, Json<Self>) {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(Self::new("SERVICE_UNAVAILABLE", message)),
        )
    }

    /// `501 Not Implemented` - `code` defaults to `"NOT_IMPLEMENTED"`.
    pub fn not_implemented(message: impl Into<String>) -> (StatusCode, Json<Self>) {
        (
            StatusCode::NOT_IMPLEMENTED,
            Json(Self::new("NOT_IMPLEMENTED", message)),
        )
    }

    /// Attach a source error message to this error.
    ///
    /// Stores the source in the details field under the `"source"` key.
    /// Can be chained with other builder methods.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum_api_kit::ApiError;
    ///
    /// let err = ApiError::new("NOT_FOUND", "user not found")
    ///     .with_source("SELECT * FROM users WHERE id = ?")
    ///     .with_details(serde_json::json!({ "user_id": 42 }));
    /// ```
    pub fn with_source(mut self, source: &str) -> Self {
        let mut details = self.details.take().unwrap_or_else(|| serde_json::json!({}));
        if let serde_json::Value::Object(ref mut map) = details {
            map.insert(
                "source".to_string(),
                serde_json::Value::String(source.to_string()),
            );
        }
        self.details = Some(details);
        self
    }
}

/// Convert `std::io::Error` to `ApiError` with HTTP 500.
///
/// Maps `std::io::Error` to `ApiError::internal()` with the error message.
/// Enables using the `?` operator in handlers:
///
/// ```rust,ignore
/// async fn handler() -> impl IntoResponse {
///     let content = std::fs::read_to_string("/data.txt")?;  // auto-converts to ApiError
///     Ok((StatusCode::OK, content))
/// }
/// ```
impl From<std::io::Error> for ApiError {
    fn from(err: std::io::Error) -> Self {
        Self::new("IO_ERROR", format!("IO error: {}", err))
    }
}

/// Convert `serde_json::Error` to `ApiError` with HTTP 500.
///
/// Maps JSON errors to `ApiError::internal()` with the error message.
impl From<serde_json::Error> for ApiError {
    fn from(err: serde_json::Error) -> Self {
        Self::new("JSON_ERROR", format!("JSON error: {}", err))
    }
}

/// Convert `sqlx::Error` to an `ApiError` with a semantically appropriate HTTP status.
///
/// Requires the `sqlx` feature flag.
///
/// | `sqlx::Error` variant | `code` | HTTP |
/// |---|---|---|
/// | `RowNotFound` | `NOT_FOUND` | 404 |
/// | `Database` (unique/FK violation) | `CONFLICT` | 409 |
/// | `Database` (check violation) | `VALIDATION_ERROR` | 422 |
/// | `Database` (other) | `DB_ERROR` | 500 |
/// | `PoolTimedOut` / `PoolClosed` / `WorkerCrashed` | `SERVICE_UNAVAILABLE` | 503 |
/// | everything else | `DB_ERROR` | 500 |
#[cfg(feature = "sqlx")]
impl From<sqlx::Error> for ApiError {
    fn from(err: sqlx::Error) -> Self {
        match err {
            sqlx::Error::RowNotFound => Self::new("NOT_FOUND", "record not found"),
            sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::WorkerCrashed => {
                Self::new("SERVICE_UNAVAILABLE", "database unavailable")
            }
            sqlx::Error::Database(db_err) => {
                if db_err.is_unique_violation() || db_err.is_foreign_key_violation() {
                    Self::new("CONFLICT", db_err.message().to_string())
                } else if db_err.is_check_violation() {
                    Self::new("VALIDATION_ERROR", db_err.message().to_string())
                } else {
                    Self::new("DB_ERROR", db_err.message().to_string())
                }
            }
            _ => Self::new("DB_ERROR", format!("database error: {}", err)),
        }
    }
}

#[cfg(feature = "validator")]
fn collect_validation_errors(
    prefix: Option<&str>,
    errors: &validator::ValidationErrors,
    out: &mut serde_json::Map<String, serde_json::Value>,
) {
    use validator::ValidationErrorsKind;

    for (field, kind) in errors.errors() {
        let base = if let Some(prefix) = prefix {
            format!("{}.{}", prefix, field)
        } else {
            field.to_string()
        };

        match kind {
            ValidationErrorsKind::Field(field_errors) => {
                let items = field_errors
                    .iter()
                    .map(|err| {
                        let mut obj = serde_json::Map::new();
                        obj.insert(
                            "code".to_string(),
                            serde_json::Value::String(err.code.to_string()),
                        );
                        if let Some(message) = &err.message {
                            obj.insert(
                                "message".to_string(),
                                serde_json::Value::String(message.to_string()),
                            );
                        }
                        if !err.params.is_empty() {
                            let params = match serde_json::to_value(&err.params) {
                                Ok(v) => v,
                                Err(_) => serde_json::Value::Null,
                            };
                            obj.insert("params".to_string(), params);
                        }
                        serde_json::Value::Object(obj)
                    })
                    .collect::<Vec<_>>();
                out.insert(base, serde_json::Value::Array(items));
            }
            ValidationErrorsKind::Struct(nested) => {
                collect_validation_errors(Some(&base), nested, out);
            }
            ValidationErrorsKind::List(items) => {
                for (index, nested) in items {
                    let indexed = format!("{}[{}]", base, index);
                    collect_validation_errors(Some(&indexed), nested, out);
                }
            }
        }
    }
}

#[cfg(feature = "validator")]
impl From<validator::ValidationErrors> for ApiError {
    fn from(errors: validator::ValidationErrors) -> Self {
        let mut fields = serde_json::Map::new();
        collect_validation_errors(None, &errors, &mut fields);

        Self::new("VALIDATION_ERROR", "validation failed").with_details(serde_json::json!({
            "fields": fields
        }))
    }
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code, self.message)
    }
}

impl std::error::Error for ApiError {}

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

    #[test]
    fn new_sets_fields() {
        let err = ApiError::new("MY_CODE", "my message");
        assert_eq!(err.code, "MY_CODE");
        assert_eq!(err.message, "my message");
        assert!(err.details.is_none());
    }

    #[test]
    fn with_details_sets_details() {
        let err = ApiError::new("CODE", "msg").with_details(json!({ "field": "name" }));
        assert_eq!(err.details.unwrap()["field"], "name");
    }

    #[test]
    fn serializes_without_details() {
        let err = ApiError::new("NOT_FOUND", "item not found");
        let v = serde_json::to_value(&err).unwrap();
        assert_eq!(v["code"], "NOT_FOUND");
        assert_eq!(v["message"], "item not found");
        assert!(v.get("details").is_none());
    }

    #[test]
    fn serializes_with_details() {
        let err = ApiError::new("VALIDATION_ERROR", "invalid").with_details(json!({ "x": 1 }));
        let v = serde_json::to_value(&err).unwrap();
        assert_eq!(v["details"]["x"], 1);
    }

    #[test]
    fn display_formats_code_and_message() {
        let err = ApiError::new("NOT_FOUND", "item not found");
        assert_eq!(err.to_string(), "NOT_FOUND: item not found");
    }

    #[test]
    fn implements_std_error() {
        let err = ApiError::new("ERR", "something failed");
        let _: &dyn std::error::Error = &err;
    }

    macro_rules! assert_factory {
        ($method:expr, $expected_status:expr, $expected_code:expr) => {{
            let (status, Json(body)) = $method;
            assert_eq!(status, $expected_status);
            assert_eq!(body.code, $expected_code);
        }};
    }

    #[test]
    fn bad_request_status_and_code() {
        assert_factory!(
            ApiError::bad_request("INVALID_FIELD", "bad"),
            StatusCode::BAD_REQUEST,
            "INVALID_FIELD"
        );
    }

    #[test]
    fn unauthorized_status_and_code() {
        assert_factory!(
            ApiError::unauthorized("please log in"),
            StatusCode::UNAUTHORIZED,
            "AUTH_REQUIRED"
        );
    }

    #[test]
    fn forbidden_status_and_code() {
        assert_factory!(
            ApiError::forbidden("no access"),
            StatusCode::FORBIDDEN,
            "FORBIDDEN"
        );
    }

    #[test]
    fn not_found_status_and_code() {
        assert_factory!(
            ApiError::not_found("missing"),
            StatusCode::NOT_FOUND,
            "NOT_FOUND"
        );
    }

    #[test]
    fn conflict_status_and_code() {
        assert_factory!(
            ApiError::conflict("already exists"),
            StatusCode::CONFLICT,
            "CONFLICT"
        );
    }

    #[test]
    fn unprocessable_status_and_code() {
        assert_factory!(
            ApiError::unprocessable("invalid input"),
            StatusCode::UNPROCESSABLE_ENTITY,
            "VALIDATION_ERROR"
        );
    }

    #[test]
    fn internal_status_and_code() {
        assert_factory!(
            ApiError::internal("oops"),
            StatusCode::INTERNAL_SERVER_ERROR,
            "INTERNAL_ERROR"
        );
    }

    #[test]
    fn db_error_status_and_code() {
        assert_factory!(
            ApiError::db_error(),
            StatusCode::INTERNAL_SERVER_ERROR,
            "DB_ERROR"
        );
    }

    #[test]
    fn too_many_requests_status_and_code() {
        assert_factory!(
            ApiError::too_many_requests("slow down"),
            StatusCode::TOO_MANY_REQUESTS,
            "RATE_LIMITED"
        );
    }

    #[test]
    fn service_unavailable_status_and_code() {
        assert_factory!(
            ApiError::service_unavailable("down for maintenance"),
            StatusCode::SERVICE_UNAVAILABLE,
            "SERVICE_UNAVAILABLE"
        );
    }

    #[test]
    fn not_implemented_status_and_code() {
        assert_factory!(
            ApiError::not_implemented("coming soon"),
            StatusCode::NOT_IMPLEMENTED,
            "NOT_IMPLEMENTED"
        );
    }

    #[test]
    fn with_source_adds_source_to_details() {
        let err = ApiError::new("NOT_FOUND", "missing").with_source("db query");
        let v = serde_json::to_value(&err).unwrap();
        assert_eq!(v["details"]["source"], "db query");
        assert_eq!(v["code"], "NOT_FOUND");
    }

    #[test]
    fn with_source_and_with_details_both_present() {
        let err = ApiError::new("ERROR", "msg")
            .with_details(json!({ "user_id": 123 }))
            .with_source("from somewhere");
        let v = serde_json::to_value(&err).unwrap();
        assert_eq!(v["details"]["source"], "from somewhere");
        assert_eq!(v["details"]["user_id"], 123);
    }

    #[test]
    fn from_io_error_creates_io_error_code() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let api_err: ApiError = io_err.into();
        assert_eq!(api_err.code, "IO_ERROR");
        assert!(api_err.message.contains("IO error"));
    }

    #[test]
    fn from_serde_json_error_creates_json_error_code() {
        let json_str = "{ invalid json }";
        let json_err: Result<serde_json::Value, _> = serde_json::from_str(json_str);
        let api_err: ApiError = json_err.unwrap_err().into();
        assert_eq!(api_err.code, "JSON_ERROR");
        assert!(api_err.message.contains("JSON error"));
    }

    #[test]
    fn io_error_conversion_captures_kind() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied");
        let api_err: ApiError = io_err.into();
        assert!(api_err.message.contains("permission denied"));
    }

    #[cfg(feature = "validator")]
    #[test]
    fn from_validation_errors_single_field() {
        use std::borrow::Cow;
        use validator::{ValidationError, ValidationErrors};

        let mut errors = ValidationErrors::new();
        let mut email = ValidationError::new("email");
        email.message = Some(Cow::Borrowed("invalid email"));
        errors.add("email", email);

        let api_err: ApiError = errors.into();
        let v = serde_json::to_value(api_err).unwrap();

        assert_eq!(v["code"], "VALIDATION_ERROR");
        assert_eq!(v["message"], "validation failed");
        assert_eq!(v["details"]["fields"]["email"][0]["code"], "email");
        assert_eq!(
            v["details"]["fields"]["email"][0]["message"],
            "invalid email"
        );
    }

    #[cfg(feature = "validator")]
    #[test]
    fn from_validation_errors_multiple_fields_with_params() {
        use std::borrow::Cow;
        use validator::{ValidationError, ValidationErrors};

        let mut errors = ValidationErrors::new();

        let mut username = ValidationError::new("length");
        username.message = Some(Cow::Borrowed("username too short"));
        username.add_param(Cow::Borrowed("min"), &3);
        errors.add("username", username);

        let mut age = ValidationError::new("range");
        age.add_param(Cow::Borrowed("min"), &18);
        errors.add("age", age);

        let api_err: ApiError = errors.into();
        let v = serde_json::to_value(api_err).unwrap();

        assert_eq!(v["details"]["fields"]["username"][0]["code"], "length");
        assert_eq!(v["details"]["fields"]["username"][0]["params"]["min"], 3);
        assert_eq!(v["details"]["fields"]["age"][0]["code"], "range");
        assert_eq!(v["details"]["fields"]["age"][0]["params"]["min"], 18);
    }

    #[cfg(feature = "sqlx")]
    #[test]
    fn sqlx_row_not_found_maps_to_not_found() {
        let api_err: ApiError = sqlx::Error::RowNotFound.into();
        assert_eq!(api_err.code, "NOT_FOUND");
        assert_eq!(api_err.message, "record not found");
    }

    #[cfg(feature = "sqlx")]
    #[test]
    fn sqlx_pool_timed_out_maps_to_service_unavailable() {
        let api_err: ApiError = sqlx::Error::PoolTimedOut.into();
        assert_eq!(api_err.code, "SERVICE_UNAVAILABLE");
    }

    #[cfg(feature = "sqlx")]
    #[test]
    fn sqlx_pool_closed_maps_to_service_unavailable() {
        let api_err: ApiError = sqlx::Error::PoolClosed.into();
        assert_eq!(api_err.code, "SERVICE_UNAVAILABLE");
    }

    #[cfg(feature = "sqlx")]
    #[test]
    fn sqlx_unknown_variant_maps_to_db_error() {
        // Protocol is a non-pool, non-database variant that hits the catch-all arm.
        let api_err: ApiError = sqlx::Error::Protocol("unexpected packet".into()).into();
        assert_eq!(api_err.code, "DB_ERROR");
        assert!(api_err.message.contains("database error"));
    }
}