rust
32 lines · 6 steps
A newtype wrapper for API tokens in Rust
Wrapping a String in a dedicated type gives cryptographically random API tokens a safe, self-documenting API.
Explained by
highlit
1use rand::distributions::{Alphanumeric, DistString};
2use rand::rngs::OsRng;
3
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct ApiToken(String);
6
7impl ApiToken {
8 const DEFAULT_LEN: usize = 40;
9
10 pub fn generate() -> Self {
11 Self::with_len(Self::DEFAULT_LEN)
12 }
13
14 pub fn with_len(len: usize) -> Self {
15 let raw = Alphanumeric.sample_string(&mut OsRng, len);
16 ApiToken(format!("sk_{raw}"))
17 }
18
19 pub fn as_str(&self) -> &str {
20 &self.0
21 }
22
23 pub fn into_inner(self) -> String {
24 self.0
25 }
26}
27
28impl std::fmt::Display for ApiToken {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.write_str(&self.0)
31 }
32}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The newtype pattern turns a bare String into a distinct type the compiler can enforce, preventing accidental misuse.
- 2Using OsRng ensures tokens draw from the operating system's cryptographically secure randomness rather than a predictable PRNG.
- 3Exposing narrow accessors like as_str and into_inner keeps the inner value controlled instead of publicly mutable.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 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
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 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/a-newtype-wrapper-for-api-tokens-in-rust-explained-rust-a113/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.