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:
[]
= "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 HttpResponse;
use Serialize;
async
Resulting Response
Otherwise if you response with an http error, for example data validation you have:
use HttpResponse;
use json;
async
Resulting Response
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 ;
async
Resulting Response
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 ;
use Serialize;
async
Resulting Response
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.