rust 59 lines · 9 steps

Building a REST resource in Axum

A full CRUD article resource wired up with Axum's Router, typed extractors, and JSON responses.

Explained by highlit
1use axum::{
2 extract::Path,
3 http::StatusCode,
4 routing::{get, post},
5 Json, Router,
6};
7use serde::{Deserialize, Serialize};
8use serde_json::{json, Value};
9 
10#[derive(Serialize)]
11struct Article {
12 id: u64,
13 title: String,
14 body: String,
15}
16 
17#[derive(Deserialize)]
18struct NewArticle {
19 title: String,
20 body: String,
21}
22 
23pub fn routes() -> Router {
24 Router::new()
25 .route("/articles", get(list_articles).post(create_article))
26 .route(
27 "/articles/:id",
28 get(show_article).put(update_article).delete(delete_article),
29 )
30}
31 
32async fn list_articles() -> Json<Vec<Article>> {
33 Json(vec![])
34}
35 
36async fn create_article(Json(input): Json<NewArticle>) -> (StatusCode, Json<Article>) {
37 let article = Article {
38 id: 1,
39 title: input.title,
40 body: input.body,
41 };
42 (StatusCode::CREATED, Json(article))
43}
44 
45async fn show_article(Path(id): Path<u64>) -> Json<Value> {
46 Json(json!({ "id": id }))
47}
48 
49async fn update_article(Path(id): Path<u64>, Json(input): Json<NewArticle>) -> Json<Article> {
50 Json(Article {
51 id,
52 title: input.title,
53 body: input.body,
54 })
55}
56 
57async fn delete_article(Path(_id): Path<u64>) -> StatusCode {
58 StatusCode::NO_CONTENT
59}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Axum extractors like Json and Path decode request data into typed values before your handler runs.
  2. 2Separate serialize and deserialize structs let outgoing and incoming shapes differ safely.
  3. 3Handlers return types that implement IntoResponse, so tuples of status plus Json map directly to HTTP responses.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a REST resource in Axum — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code