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 like macros to reduce boilerplate code.
Installation
Add the dependency to your Cargo.toml:
[]
= "0.3.1"
Make sure to also include the necessary dependencies such as 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 creating responses with custom status codes and bodies. - Integration with Axum: Specifically designed to work with the Axum framework.
Example Usage
use ;
use Response;
use json;
async
async
Using HttpResponse for More Flexible Responses
The HttpResponse structure allows you to build responses with a status code, JSON body, and custom headers using a builder pattern.
use HttpResponse;
use StatusCode;
use json;
use Serialize;
// Simple handler using HttpResponse
async
// Handler using the `json()` method to serialize structs
async
// Example in an Axum application
use ;
response! Macro
The response! macro allows you to create HttpResponse responses with a status code and a JSON body more concisely. It also supports auto-serialization of structs that implement Serialize.
use ;
use Serialize;
async
async
async
async
// Example in an Axum application
use ;
Differences Between Response and HttpResponse
-
Response: An enum designed to handle standard and custom responses in a simple way. It is useful for handlers that need to return predefined responses. -
HttpResponse: A more flexible structure that lets you define a status code and arbitrary JSON body. It's ideal for cases where you need more granular control over the response using a builder-style pattern.
Both types implement the IntoResponse trait, which means they can be used directly as responses in Axum.