Unified, type-safe API response builder for Axum applications.
This crate provides a simple and consistent way to build JSON API responses in Axum web applications. It ensures a unified format for both success and error responses, making your APIs easier to maintain and consume.
- Type-safe responses: Use generics to ensure your data is serialized correctly.
- Consistent structure: All responses follow the same JSON format with
status, optionaldata, and optionalmessage. - Easy integration: Designed specifically for Axum, with direct support for
IntoResponse. - Lightweight: Minimal dependencies, focused on simplicity.
Add the following to your Cargo.toml:
[dependencies]
response = "1"This crate depends on axum, serde, and serde_json, so ensure they are included in your project as well (or let Cargo handle them via transitive dependencies).
Import the crate and use the success and error functions in your Axum handlers.
All responses are serialized to JSON in the following format:
{
"status": "success" | "error",
"data": { ... } // Optional, for success responses
"message": "..." // Optional, for error responses
}Use success to return a 200 OK response with data:
use response::success;
use axum::response::IntoResponse;
use serde::Serialize;
async fn handler() -> impl IntoResponse {
success(serde_json::json!({
"key": "value"
}))
}Use error to return an error response with a custom status code and message:
use response::error;
use axum::http::StatusCode;
use axum::response::IntoResponse;
async fn handler() -> impl IntoResponse {
error(StatusCode::BAD_REQUEST, "Invalid input".to_string())
}A complete demo is available in examples/demo.rs. Here's a snippet:
use axum::http::StatusCode;
use axum::{Router, routing::get};
use response::{error, success};
use std::net::SocketAddr;
use tokio::net::TcpListener;
async fn success_handler() -> impl axum::response::IntoResponse {
success(serde_json::json!({
"message": "Everything is fine!"
}))
}
async fn error_handler() -> impl axum::response::IntoResponse {
error(StatusCode::BAD_REQUEST, "Something went wrong.".to_string())
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/success", get(success_handler))
.route("/error", get(error_handler));
let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
println!("Listening on http://{}", addr);
let listener = TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}To run the example:
- Clone the repository:
git clone https://github.com/canmi21/response.git - Navigate to the project:
cd response - Run the example:
cargo run --example demo - Access
http://localhost:8080/successorhttp://localhost:8080/errorin your browser or via curl.
This project is licensed under the MIT License. See the LICENSE file for details.
Contributions are welcome! Please open an issue or submit a pull request on GitHub.