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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Returning a per-item result list lets one bad entry fail without sinking the whole batch.
  2. 2Serde's skip_serializing_if keeps response bodies clean by omitting fields that don't apply.
  3. 3Mapping each error variant to a distinct HTTP status communicates intent to the client precisely.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Batch inserts with per-item status in Axum — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code