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 std::convert::TryFrom; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HttpStatus {
Converting HTTP codes with TryFrom in Rust
enums
error-handling
trait-implementation
Intermediate
8 steps
rust
use axum::{ extract::{Request, State}, http::{HeaderValue, StatusCode}, middleware::Next,
API version headers with Axum middleware
middleware
http-headers
versioning
Intermediate
8 steps
javascript
import { NavLink, useLocation } from 'react-router-dom'; const NAV_ITEMS = [ { to: '/', label: 'Dashboard', end: true },
Building an accessible Sidebar in React
routing
accessibility
declarative-ui
Intermediate
6 steps
rust
use chrono::NaiveDate; use serde::{Deserialize, Deserializer}; #[derive(Debug, Deserialize)]
Custom date parsing with serde in Rust
serde
deserialization
csv-parsing
Intermediate
7 steps
rust
use axum::{extract::State, http::StatusCode, Json}; use serde::{Deserialize, Serialize}; use sqlx::PgPool; use uuid::Uuid;
An atomic money transfer handler in Axum
database-transactions
atomicity
error-handling
Intermediate
9 steps
typescript
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, DeepPartial } from 'typeorm'; import { User } from './entities/user.entity';
Building a CRUD service in NestJS
crud
dependency-injection
repository-pattern
Intermediate
7 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.