axum_api_kit/lib.rs
1//! Shared response types for Axum JSON APIs.
2//!
3//! Provides building blocks that every Axum CRUD service needs but always
4//! re-defines from scratch:
5//!
6//! - [`ApiError`] - a machine-readable JSON error body with `code`, `message`, and optional
7//! `details`, plus factory helpers that return `(StatusCode, Json<ApiError>)` tuples ready
8//! for use with Axum's [`IntoResponse`](axum::response::IntoResponse). The
9//! `too_many_requests_with_retry_after` and `service_unavailable_with_retry_after`
10//! factories additionally emit a delay-seconds `Retry-After` header. Supports `From`
11//! conversions for common error types. With the optional `validator` feature enabled,
12//! also supports converting `validator::ValidationErrors` into structured field errors.
13//! With the optional `sqlx` feature enabled, also supports converting `sqlx::Error` into
14//! semantically correct HTTP status codes (404, 409, 422, 503, 500).
15//! - [`ListResponse<T>`] - a generic offset/limit paginated collection response with `data`,
16//! `total`, `limit`, and `offset` fields.
17//! - [`CursorResponse<T>`] - a generic cursor-based paginated collection response for large
18//! datasets or feeds, with `data`, `next_cursor`, and `has_more` fields.
19//! - [`HealthResponse`] - a health-check response with `status` field supporting `ok`,
20//! `degraded`, and `unhealthy` states.
21//! - [`Created<T>`], [`Accepted<T>`], and [`NoContent`] - success-side responses for the
22//! rest of the CRUD lifecycle: `201 Created` (with an optional `Location` header),
23//! `202 Accepted`, and `204 No Content`.
24//!
25//! With optional feature flags enabled, the kit also provides request extractors that
26//! reject with an [`ApiError`] body on failure:
27//!
28//! - `ValidatedJson<T>` (feature `validator`) - deserializes a JSON body and runs
29//! `validator` validation before the handler runs.
30//! - `Pagination` and `CursorPagination` (feature `extract`) - parse `limit`/`offset` and
31//! `cursor`/`limit` query parameters into typed values, with `list_response` /
32//! `cursor_response` helpers that build the matching response type.
33//! - `ApiJson<T>` (feature `extract`) - a drop-in replacement for `axum::Json` whose
34//! extraction failures reject with an `ApiError` body instead of Axum's plain-text default.
35//!
36//! It also ships observability middleware:
37//!
38//! - `propagate_request_id` and `trace_requests` (feature `trace`) - assign an
39//! `x-request-id` correlation id (extractable via `RequestId`) and emit a structured
40//! `tracing` event with method, path, status, and latency for each request.
41//!
42//! And service-wiring helpers:
43//!
44//! - `health_routes` and `liveness` (feature `router`) - a `Router` exposing `/healthz` and
45//! `/readyz` probes backed by `HealthResponse`.
46//! - `cors_allowing` and `cors_permissive` (feature `cors`) - build a `tower_http`
47//! `CorsLayer` with sensible defaults.
48//!
49//! And an RFC 9457 error format:
50//!
51//! - `Problem` (feature `problem`) - an RFC 9457 problem+json response type with builder
52//! methods, lossless bridges from [`ApiError`], and Retry-After support. Emits
53//! `Content-Type: application/problem+json`.
54//!
55//! With the `openapi` feature, all four response types derive `utoipa::ToSchema` so they
56//! can be referenced from a `utoipa` `OpenApi` document and appear in generated specs.
57//!
58//! # Quick Start
59//!
60//! ```rust,no_run
61//! use axum::{Json, http::StatusCode, response::IntoResponse};
62//! use axum_api_kit::{ApiError, ListResponse, CursorResponse, HealthResponse};
63//! use serde::Serialize;
64//!
65//! #[derive(Serialize)]
66//! struct Item { id: String }
67//!
68//! async fn list_items() -> impl IntoResponse {
69//! let items = vec![Item { id: "1".into() }];
70//! Json(ListResponse { data: items, total: 1, limit: 50, offset: 0 })
71//! }
72//!
73//! async fn feed_items(cursor: Option<String>) -> impl IntoResponse {
74//! let items = vec![Item { id: "1".into() }];
75//! CursorResponse { data: items, next_cursor: Some("abc".into()), has_more: true }
76//! }
77//!
78//! async fn get_item() -> impl IntoResponse {
79//! ApiError::not_found("item not found")
80//! }
81//!
82//! async fn health() -> impl IntoResponse {
83//! HealthResponse::ok()
84//! }
85//! ```
86
87#[cfg(feature = "extract")]
88mod apijson;
89#[cfg(feature = "cors")]
90mod cors;
91mod cursor;
92mod error;
93mod health;
94mod list;
95#[cfg(feature = "extract")]
96mod pagination;
97#[cfg(feature = "problem")]
98mod problem;
99#[cfg(feature = "router")]
100mod router;
101mod success;
102#[cfg(feature = "trace")]
103mod trace;
104#[cfg(feature = "validator")]
105mod validated;
106
107#[cfg(feature = "extract")]
108pub use apijson::ApiJson;
109#[cfg(feature = "cors")]
110pub use cors::{cors_allowing, cors_permissive};
111pub use cursor::CursorResponse;
112pub use error::ApiError;
113pub use health::HealthResponse;
114pub use list::ListResponse;
115#[cfg(feature = "extract")]
116pub use pagination::{CursorPagination, Pagination};
117#[cfg(feature = "problem")]
118pub use problem::{Problem, APPLICATION_PROBLEM_JSON};
119#[cfg(feature = "router")]
120pub use router::{health_routes, liveness};
121pub use success::{Accepted, Created, NoContent};
122#[cfg(feature = "trace")]
123pub use trace::{propagate_request_id, trace_requests, RequestId, REQUEST_ID_HEADER};
124#[cfg(feature = "validator")]
125pub use validated::ValidatedJson;