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