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 to handle standard and custom responses, along with useful tools like macros to reduce code repetition.
Installation
Add the dependency to your Cargo.toml file:
[]
= "0.2.0"
Make sure to also include the necessary dependencies like axum, serde, and serde_json.
Features
- Standard and custom responses: Handle common HTTP responses like
200 OK,404 Not Found. - Useful macros: Use the
response!macro to simplify the creation of responses with status codes and custom bodies. - Integration with Axum: Specifically designed to work with the Axum framework.
- Error handling: Facilitates the propagation of HTTP errors in your controllers using types like
ControllerResultorHandlerResult.
Usage Example
Standard and Custom Responses
The Response enum includes variants for the most common HTTP status codes, such as Response::OK, Response::NOT_FOUND, and more. You can also create custom responses with Response::CUSTOM.
use ;
use Response;
use json;
async
async
Macro response!
The response! macro allows you to create responses with a status code and a JSON body more concisely. This macro returns a Result, where responses with successful status codes (200..399) are wrapped in Ok, and others in Err.
use ;
async
async
async
Differences Between Response and HttpResponse
Response: An enumeration designed to handle standard and custom responses easily. It is useful for controllers that need to return predefined responses.HttpResponse: A more flexible structure that allows you to define an arbitrary status code and JSON body. It is ideal for cases where you need more granular control over the response.
Both types implement the IntoResponse trait, meaning they can be used directly as responses in Axum.
Considerations
- Compatibility Between
ResponseandHttpResponse: Although both implementIntoResponse, they are not directly interchangeable. UseResponsefor standard responses andHttpResponsefor custom ones. - Using the
response!Macro: This macro returns aResult, which can be useful for handling errors in controllers. However, note that this may not be a common practice in Axum, as controllers typically return a type that directly implementsIntoResponse. Therefore, you should always use aResultin the controller. For this, theControllerResultandHandlerResulttypes were introduced, both being aliases forResult<HttpResponse, HttpResponse>. - Macro Errors: If you use an invalid status code in the
response!macro, it will generate apanic!. Make sure to use valid codes.