21 unstable releases (3 breaking)
| 0.4.6 | Oct 31, 2025 |
|---|---|
| 0.4.4 | Sep 29, 2025 |
| 0.4.2 | Jul 3, 2025 |
| 0.1.7 | May 21, 2024 |
| 0.1.4 | Mar 22, 2024 |
#424 in Rust patterns
68 downloads per month
Used in sword
39KB
588 lines
Axum Responses
Description
Axum Responses is a library designed to simplify the creation and handling of HTTP responses in applications built with Axum. It provides a clear abstraction for handling standard and custom responses, along with useful tools.
Installation
Add the dependency to your Cargo.toml:
[dependencies]
axum_responses = "0.4.6"
Features
- Standard and Custom Responses: Handle common HTTP responses like
200 OK,404 Not Found. - Useful Macro: Use the
response!macro to simplify creating responses with custom status codes and bodies. - Integration with Axum: Specifically designed to work with the Axum framework.
- RFC Conventions: Follows RFC conventions for HTTP responses, ensuring consistency and clarity in your API responses.
Usage
The HttpResponse Structure
This structure allows you to build responses with a status code, JSON body, and custom headers using a builder pattern.
use axum_responses::http::HttpResponse;
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u32,
username: String,
}
async fn handler() -> HttpResponse {
let user_data = User {
id: 1,
username: "example_user".to_string(),
};
HttpResponse::Created()
.message("User data retrieved successfully")
.data(user_data)
}
Resulting Response
{
"code": 201,
"success": true,
"message": "User data retrieved successfully",
"timestamp": "2023-10-01T12:00:00Z",
"data": {
"id": 1,
"username": "example_user"
}
}
Otherwise if you response with an http error, for example data validation you have:
use axum_responses::http::HttpResponse;
use serde_json::json;
async fn error_handler() -> HttpResponse {
let validation_error = json!({
"type": "ValidationError",
"errors": [
{
"field": "username",
"message": "Username is required"
},
{
"field": "email",
"message": "Email must be a valid email address"
}
]
});
HttpResponse::BadRequest()
.message("Invalid request data")
.error(validation_error)
}
Resulting Response
{
"code": 400,
"success": false,
"message": "Invalid request data",
"timestamp": "2023-10-01T12:00:00Z",
"error": {
"type": "ValidationError",
"errors": [
{
"field": "username",
"message": "Username is required"
},
{
"field": "email",
"message": "Email must be a valid email address"
}
]
}
}
The response! Macro
The response! macro allows you to create HttpResponse responses with a status code and a JSON body being more lax. It also supports auto-serialization of structs that implement Serialize.
use axum_responses::{response, http::HttpResponse};
async fn example_handler() -> HttpResponse {
response!(200, { "page": 10, "total": 100, "message": "Success Response (OK)" })
}
Resulting Response
{
"code": 200,
"success": true,
"message": "Success Response (OK)",
"timestamp": "2023-10-01T12:00:00Z",
"data": {
"page": 10,
"total": 100
}
}
The macro also supports single objects in the data field, which is useful for returning a single resource or entity. This is designed to be similar to javascript notation.
use axum_responses::{response, http::HttpResponse};
use serde::Serialize;
#[derive(Serialize)]
struct Product {
id: String,
name: String,
price: f64,
}
async fn product_handler() -> HttpResponse {
let product_data = Product {
id: "prod_123".to_string(),
name: "Example Product".to_string(),
price: 99.99,
};
response!(201, { product_data })
}
Resulting Response
{
"code": 201,
"success": true,
"message": "Created",
"timestamp": "2023-10-01T12:00:00Z",
"data": {
"id": "prod_123",
"name": "Example Product",
"price": 99.99
}
}
Breaking Changes
-
If the methods
data,error, orerrorsare not called, those fields will no longer appear in the final response. Previously, thedatafield was included withnullvalue. -
Remove previosly marked
deprecatedResponseenum. -
The
Responseenum has been deprecated in favor of theHttpResponsestructure. -
The
ControllerResulttype has been removed, and now you can useResult<T, HttpResponse>directly in your handlers, create your own custom Result type, or just useHttpResponsedirectly. -
The library now implements RFC conventions for HTTP responses.
Dependencies
~6–10MB
~184K SLoC