Expand description
Shared response types for Axum JSON APIs.
Provides building blocks that every Axum CRUD service needs but always re-defines from scratch:
ApiError- a machine-readable JSON error body withcode,message, and optionaldetails, plus factory helpers that return(StatusCode, Json<ApiError>)tuples ready for use with Axum’sIntoResponse. SupportsFromconversions for common error types. With the optionalvalidatorfeature enabled, also supports convertingvalidator::ValidationErrorsinto structured field errors. With the optionalsqlxfeature enabled, also supports convertingsqlx::Errorinto semantically correct HTTP status codes (404, 409, 422, 503, 500).ListResponse<T>- a generic offset/limit paginated collection response withdata,total,limit, andoffsetfields.CursorResponse<T>- a generic cursor-based paginated collection response for large datasets or feeds, withdata,next_cursor, andhas_morefields.HealthResponse- a health-check response withstatusfield supportingok,degraded, andunhealthystates.
With optional feature flags enabled, the kit also provides request extractors that
reject with an ApiError body on failure:
ValidatedJson<T>(featurevalidator) - deserializes a JSON body and runsvalidatorvalidation before the handler runs.PaginationandCursorPagination(featureextract) - parselimit/offsetandcursor/limitquery parameters into typed values, withlist_response/cursor_responsehelpers that build the matching response type.
It also ships observability middleware:
propagate_request_idandtrace_requests(featuretrace) - assign anx-request-idcorrelation id (extractable viaRequestId) and emit a structuredtracingevent with method, path, status, and latency for each request.
And service-wiring helpers:
health_routesandliveness(featurerouter) - aRouterexposing/healthzand/readyzprobes backed byHealthResponse.cors_allowingandcors_permissive(featurecors) - build atower_httpCorsLayerwith sensible defaults.
With the openapi feature, all four response types derive utoipa::ToSchema so they
can be referenced from a utoipa OpenApi document and appear in generated specs.
§Quick Start
use axum::{Json, http::StatusCode, response::IntoResponse};
use axum_api_kit::{ApiError, ListResponse, CursorResponse, HealthResponse};
use serde::Serialize;
#[derive(Serialize)]
struct Item { id: String }
async fn list_items() -> impl IntoResponse {
let items = vec![Item { id: "1".into() }];
Json(ListResponse { data: items, total: 1, limit: 50, offset: 0 })
}
async fn feed_items(cursor: Option<String>) -> impl IntoResponse {
let items = vec![Item { id: "1".into() }];
CursorResponse { data: items, next_cursor: Some("abc".into()), has_more: true }
}
async fn get_item() -> impl IntoResponse {
ApiError::not_found("item not found")
}
async fn health() -> impl IntoResponse {
HealthResponse::ok()
}Structs§
- ApiError
- A machine-readable JSON error body.
- Cursor
Pagination - Cursor-based pagination parameters parsed from the query string.
- Cursor
Response - A cursor-based paginated collection response.
- Health
Response - A minimal health-check response body.
- List
Response - A generic paginated collection response.
- Pagination
- Offset/limit pagination parameters parsed from the query string.
- Request
Id - A request correlation id, stored in request extensions by
propagate_request_id. - Validated
Json - An Axum extractor that deserializes a JSON request body and validates it with
validator.
Constants§
- REQUEST_
ID_ HEADER - The header used to carry the request correlation id:
x-request-id.
Functions§
- cors_
allowing - Build a CORS layer that allows the given origins.
- cors_
permissive - A permissive CORS layer (any origin, method, and header).
- health_
routes - Build a
Routerexposing/healthz(liveness) and/readyz(readiness) probes. - liveness
- Liveness probe handler: always returns
HealthResponse::ok. - propagate_
request_ id - Axum middleware that assigns a request correlation id and echoes it on the response.
- trace_
requests - Axum middleware that emits a structured
tracingevent when each request completes.