Skip to main content
The Json extractor and response type makes it easy to work with JSON data in Axum applications.

Extracting JSON request bodies

Use the Json 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

Return Json to automatically serialize responses:
This automatically sets the Content-Type: application/json header and serializes the struct.

Working with generic JSON

Use serde_json::Value for dynamic JSON:

Complete CRUD example

Here’s a full REST API example:

Error handling

Handle JSON deserialization errors:

JSON error types

The Json extractor can fail with these errors:
  • MissingJsonContentType: Request missing Content-Type: application/json header (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

The Json 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

The Json extractor must be the last extractor in a handler if you have multiple extractors, since it consumes the request body.
Always use strongly-typed structs instead of Value when possible. This provides better type safety and clearer API documentation.
Use #[serde(rename_all = "camelCase")] on your structs to automatically convert between Rust’s snake_case and JSON’s camelCase conventions.