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
go
func UploadDocument(c *gin.Context) { fileHeader, err := c.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
Handling multipart uploads in Gin
multipart-upload
validation
error-handling
Intermediate
9 steps
rust
use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use axum::body::Body;
A maintenance-mode gate in Axum
middleware
shared-state
atomics
Intermediate
7 steps
rust
use axum::body::Bytes; use axum::http::{header, HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; use serde::Serialize;
Custom Axum responses with per-user ETags
etag
trait-implementation
generics
Intermediate
7 steps
rust
use std::time::Duration; #[derive(Debug, PartialEq)] pub enum ParseDurationError {
Parsing duration strings safely in Rust
parsing
error-handling
checked-arithmetic
Intermediate
8 steps
ruby
module Rack class MaintenanceMode RETRY_AFTER = 3600
A Rack maintenance-mode middleware in Rails
middleware
rack
http-status
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 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.