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
php
<?php namespace App\Validation;
Building a reusable address form validator in PHP
validation
error-accumulation
regex
Intermediate
9 steps
ruby
require 'date' require 'set' class BusinessDayCalculator
Counting business days in Ruby
dates
sets
ranges
Intermediate
8 steps
rust
pub fn normalize_path(input: &str) -> String { let is_absolute = input.starts_with('/'); let has_trailing_slash = input.len() > 1 && input.ends_with('/'); let mut stack: Vec<&str> = Vec::new();
Normalizing filesystem paths in Rust
string-processing
stack
path-manipulation
Intermediate
8 steps
rust
use axum::{ extract::Query, response::IntoResponse, Json,
Parsing query strings in Axum handlers
deserialization
query-parameters
defaults
Intermediate
7 steps
rust
use axum::{ body::{Body, Bytes}, extract::Request, http::StatusCode,
Logging request and response sizes in Axum
middleware
http
streaming-bodies
Advanced
8 steps
rust
use std::borrow::Cow; pub fn escape_html(input: &str) -> Cow<'_, str> { let needs_escape = input
Zero-copy HTML escaping with Cow in Rust
clone-on-write
zero-copy
string-escaping
Intermediate
6 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.