Json extractor and response type makes it easy to work with JSON data in Axum applications.
Extracting JSON request bodies
Use theJson extractor to deserialize JSON from request bodies:
Basic JSON extraction
1
Define your data structure
Create a struct that implements
Deserialize:2
Use the Json extractor
Extract JSON in your handler:
3
Set up the route
The
Json extractor requires the request to have a Content-Type: application/json header. Requests without this header will be rejected with a 415 Unsupported Media Type error.JSON responses
ReturnJson to automatically serialize responses:
Content-Type: application/json header and serializes the struct.
Working with generic JSON
Useserde_json::Value for dynamic JSON:
Complete CRUD example
Here’s a full REST API example:Error handling
Handle JSON deserialization errors:JSON error types
TheJson extractor can fail with these errors:
JSON rejection types
JSON rejection types
MissingJsonContentType: Request missingContent-Type: application/jsonheader (HTTP 415)JsonDataError: JSON is valid but doesn’t match the target type (HTTP 422)JsonSyntaxError: Invalid JSON syntax (HTTP 400)BytesRejection: Failed to buffer request body
Content type variants
TheJson extractor accepts various JSON content types:
Response customization
Customize JSON responses with status codes and headers:Performance optimization
For large JSON payloads, consider streaming:Testing JSON handlers
Best practices
Always use strongly-typed structs instead of
Value when possible. This provides better type safety and clearer API documentation.