rust
70 lines · 8 steps
Batch inserts with per-item status in Axum
An Axum handler processes a list of contacts one by one and reports an individual outcome for each, instead of failing the whole batch.
Explained by
highlit
1use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
2use serde::{Deserialize, Serialize};
3use std::sync::Arc;
4
5#[derive(Deserialize)]
6pub struct NewContact {
7 pub email: String,
8 pub name: String,
9}
10
11#[derive(Serialize)]
12pub struct ItemResult {
13 pub index: usize,
14 pub status: u16,
15 #[serde(skip_serializing_if = "Option::is_none")]
16 pub id: Option<i64>,
17 #[serde(skip_serializing_if = "Option::is_none")]
18 pub error: Option<String>,
19}
20
21pub async fn create_contacts(
22 State(repo): State<Arc<ContactRepo>>,
23 Json(contacts): Json<Vec<NewContact>>,
24) -> impl IntoResponse {
25 let mut results = Vec::with_capacity(contacts.len());
26
27 for (index, contact) in contacts.into_iter().enumerate() {
28 let item = match validate(&contact) {
29 Err(msg) => ItemResult {
30 index,
31 status: StatusCode::UNPROCESSABLE_ENTITY.as_u16(),
32 id: None,
33 error: Some(msg),
34 },
35 Ok(()) => match repo.insert(&contact).await {
36 Ok(id) => ItemResult {
37 index,
38 status: StatusCode::CREATED.as_u16(),
39 id: Some(id),
40 error: None,
41 },
42 Err(RepoError::Duplicate) => ItemResult {
43 index,
44 status: StatusCode::CONFLICT.as_u16(),
45 id: None,
46 error: Some("email already exists".into()),
47 },
48 Err(e) => ItemResult {
49 index,
50 status: StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
51 id: None,
52 error: Some(e.to_string()),
53 },
54 },
55 };
56 results.push(item);
57 }
58
59 (StatusCode::MULTI_STATUS, Json(results))
60}
61
62fn validate(contact: &NewContact) -> Result<(), String> {
63 if !contact.email.contains('@') {
64 return Err("invalid email".into());
65 }
66 if contact.name.trim().is_empty() {
67 return Err("name is required".into());
68 }
69 Ok(())
70}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Returning a per-item result list lets one bad entry fail without sinking the whole batch.
- 2Serde's skip_serializing_if keeps response bodies clean by omitting fields that don't apply.
- 3Mapping each error variant to a distinct HTTP status communicates intent to the client precisely.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 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
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/batch-inserts-with-per-item-status-in-axum-explained-rust-97f0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.