rust
53 lines · 7 steps
A custom tenant extractor in Axum
Implementing FromRequestParts lets a handler pull a validated X-Tenant-Id header straight from its arguments.
Explained by
highlit
1use axum::{
2 async_trait,
3 extract::FromRequestParts,
4 http::{header::HeaderName, request::Parts, StatusCode},
5 response::{IntoResponse, Response},
6 Json,
7};
8use serde_json::json;
9
10static X_TENANT_ID: HeaderName = HeaderName::from_static("x-tenant-id");
11
12pub struct TenantId(pub String);
13
14pub enum TenantRejection {
15 Missing,
16 Invalid,
17}
18
19impl IntoResponse for TenantRejection {
20 fn into_response(self) -> Response {
21 let message = match self {
22 TenantRejection::Missing => "missing required X-Tenant-Id header",
23 TenantRejection::Invalid => "X-Tenant-Id header is not valid UTF-8",
24 };
25 (StatusCode::BAD_REQUEST, Json(json!({ "error": message }))).into_response()
26 }
27}
28
29#[async_trait]
30impl<S> FromRequestParts<S> for TenantId
31where
32 S: Send + Sync,
33{
34 type Rejection = TenantRejection;
35
36 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
37 let value = parts
38 .headers
39 .get(&X_TENANT_ID)
40 .ok_or(TenantRejection::Missing)?;
41
42 let tenant = value
43 .to_str()
44 .map_err(|_| TenantRejection::Invalid)?
45 .trim();
46
47 if tenant.is_empty() {
48 return Err(TenantRejection::Missing);
49 }
50
51 Ok(TenantId(tenant.to_owned()))
52 }
53}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing FromRequestParts turns a plain struct into a reusable, self-validating handler argument.
- 2Pairing an extractor with an IntoResponse rejection keeps failure paths as first-class, well-typed responses.
- 3The ? operator chains header lookup, decoding, and validation into a single clean fallible flow.
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
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 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
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/a-custom-tenant-extractor-in-axum-explained-rust-cd79/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.