rust
50 lines · 7 steps
Building a typed create_user handler in Axum
An Axum POST handler that deserializes JSON, validates, inserts via sqlx, and returns a typed 201 response.
Explained by
highlit
1use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
2use serde::{Deserialize, Serialize};
3use uuid::Uuid;
4
5#[derive(Debug, Deserialize)]
6pub struct CreateUser {
7 name: String,
8 email: String,
9 #[serde(default)]
10 role: Role,
11}
12
13#[derive(Debug, Default, Deserialize, Serialize)]
14#[serde(rename_all = "lowercase")]
15pub enum Role {
16 #[default]
17 Member,
18 Admin,
19}
20
21#[derive(Debug, Serialize)]
22pub struct UserResponse {
23 id: Uuid,
24 name: String,
25 email: String,
26 role: Role,
27}
28
29pub async fn create_user(
30 State(pool): State<PgPool>,
31 Json(payload): Json<CreateUser>,
32) -> Result<impl IntoResponse, ApiError> {
33 if payload.email.trim().is_empty() {
34 return Err(ApiError::UnprocessableEntity("email is required".into()));
35 }
36
37 let user = sqlx::query_as!(
38 UserResponse,
39 r#"INSERT INTO users (name, email, role)
40 VALUES ($1, $2, $3)
41 RETURNING id, name, email, role AS "role: Role""#,
42 payload.name,
43 payload.email,
44 payload.role as Role,
45 )
46 .fetch_one(&pool)
47 .await?;
48
49 Ok((StatusCode::CREATED, Json(user)))
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Deriving Deserialize and Serialize lets serde map JSON directly onto strongly-typed structs and enums.
- 2Axum extractors like State and Json declare a handler's dependencies and inputs in its signature.
- 3sqlx's query_as! checks SQL against the database at compile time and maps rows straight into a struct.
Related explainers
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js'; export interface NormalizedPhone { e164: string;
Normalizing phone numbers to E.164 in TypeScript
validation
normalization
error-handling
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-typed-create_user-handler-in-axum-explained-rust-5f2a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.