JSON and State
Shared state and serialization.
Returning JSON
Axum makes JSON responses easy. Wrap any Serialize type in Json and it sets the content type and serializes the body.
use axum::Json;
use serde::Serialize;
#[derive(Serialize)]
struct User { id: u32, name: String }
async fn get_user() -> Json<User> {
Json(User { id: 1, name: "Alice".into() })
}Serializing collections
A Vec of serializable items becomes a JSON array. No extra work needed.
use axum::Json;
use serde::Serialize;
#[derive(Serialize)]
struct Item { id: u32 }
async fn list() -> Json<Vec<Item>> {
Json(vec![Item { id: 1 }, Item { id: 2 }])
}All lessons in this course
- Axum Routing
- Extractors
- JSON and State
- Middleware