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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Axum extractors like Json and Path decode request data into typed values before your handler runs.
- 2Separate serialize and deserialize structs let outgoing and incoming shapes differ safely.
- 3Handlers return types that implement IntoResponse, so tuples of status plus Json map directly to HTTP responses.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-rest-resource-in-axum-explained-rust-e956/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.