Axum Responses
Simplify HTTP responses and error handling in axum based applications.
It uses a builder pattern to create standardized JSON responses, file responses, and derive macro to declare, manage, log, and convert errors into standarized json responses.
Installation
Add the dependency to your Cargo.toml:
[]
= "0.5.4"
# For data serialization and deserialization
= { = "*", = ["derive"] }
Usage
The JsonResponse Structure
This structure allows you to build responses with a status code, JSON body, and custom headers using a builder pattern.
use JsonResponse;
use Serialize;
async
Resulting Response
Error Handling with HttpError
Define custom error types that automatically convert to JSON responses:
use ;
Use in handlers:
use IntoResponse;
async
The http attibute converts the error into a JsonResponse with the specified status code, and optionally other fields that are defined in the builder of JsonResponse. In the same way, if you dont provide a message field, it will use the cannonical message for that status code.
Examples
You can find complete examples in the examples directory, including advanced usage with tracing, thiserror attributes, and other features.
Breaking Changes
-
From
HttpResponsetoJsonResponse: The main response structure has been renamed to better reflect its purpose of handling JSON responses. -
add_headerMethod: The method to add custom headers has been renamed fromadd_headertoheaderfor improved clarity.