Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: A URL Shortener

Design and build a URL shortener service with Axum and SQLx. Plan the routes and schema, generate short codes, validate URLs, redirect and count clicks, with runnable Rust stand-ins.

A URL shortener looks tiny, but it touches nearly everything you have learned: routing with path parameters, JSON bodies, validation, a database with a unique constraint, redirects with the right status code, error mapping and tests. In this project you plan the service, read the real Axum and SQLx code for it, and run the core logic as plain Rust.

The real crates cannot run on this site, so the Axum and SQLx code is read-only. The logic that actually needs care (code generation, URL validation, the redirect decision) is written as runnable stand-ins you can experiment with.

The plan

Routes:

Method Path Behavior
POST /api/links Body {"url": "..."}; returns 201 with the short code
GET /{code} Redirects to the target (302), or 404
GET /api/links/{code}/stats Returns the click count
GET /healthz Liveness

Schema (migration 0001_links.sql):

SQL
CREATE TABLE links (
    id         BIGSERIAL PRIMARY KEY,
    code       TEXT NOT NULL UNIQUE,
    target_url TEXT NOT NULL,
    clicks     BIGINT NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
flowchart LR
    C["Client"] -->|"POST /api/links"| A["create_link"]
    A -->|"validate URL, make code"| D[("links table")]
    C2["Browser"] -->|"GET /aZ3k"| R["redirect"]
    R -->|"UPDATE clicks, SELECT target"| D
    R -->|"302 Location: target"| C2

Creating a link writes one row; following a link reads it and bumps its counter.

Short codes with base 62

A short code is a number written in a larger alphabet. Base 62 (0-9, a-z, A-Z) packs a lot into few characters: six characters cover over 56 billion values. Deriving the code from the row's id guarantees uniqueness without retry loops, though sequential codes are guessable. For private links, generate random codes and retry on a unique-constraint violation.

Rust Base 62 encoding and decoding (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Validating the target URL

Never trust the input. A shortener that accepts javascript:alert(1) or file:///etc/passwd is a security hole. Accept only http and https, require a host, cap the length and reject whitespace. In real code use the url crate; the stand-in shows the rules.

Rust Validate and normalize a target URL (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The real Axum handlers

Rust
#[derive(Clone)]
struct AppState { pool: PgPool, base_url: String }

#[derive(Deserialize)]
struct CreateLink { url: String }

#[derive(Serialize)]
struct LinkCreated { code: String, short_url: String }

async fn create_link(
    State(state): State<AppState>,
    Json(body): Json<CreateLink>,
) -> Result<(StatusCode, Json<LinkCreated>), AppError> {
    let target = validate(&body.url).map_err(|_| AppError::Invalid("url must be http(s)".into()))?;

    // Insert first to get the id, then derive the code from it.
    let id: i64 = sqlx::query_scalar(
        "INSERT INTO links (code, target_url) VALUES ('', $1) RETURNING id",
    )
    .bind(&target)
    .fetch_one(&state.pool)
    .await?;
    let code = encode(id as u64);
    sqlx::query("UPDATE links SET code = $1 WHERE id = $2")
        .bind(&code)
        .bind(id)
        .execute(&state.pool)
        .await?;

    let short_url = format!("{}/{}", state.base_url, code);
    Ok((StatusCode::CREATED, Json(LinkCreated { code, short_url })))
}

async fn redirect(
    State(state): State<AppState>,
    Path(code): Path<String>,
) -> Result<Redirect, AppError> {
    let target: Option<String> = sqlx::query_scalar(
        "UPDATE links SET clicks = clicks + 1 WHERE code = $1 RETURNING target_url",
    )
    .bind(&code)
    .fetch_optional(&state.pool)
    .await?;

    target.map(|url| Redirect::temporary(&url)).ok_or(AppError::NotFound)
}

Two decisions to notice. The redirect uses a single UPDATE ... RETURNING, so reading and counting happen atomically with one round trip. And it uses 302/307 (temporary) rather than 301: browsers cache permanent redirects forever, which would stop clicks from being counted and make link edits impossible.

In the router, register /{code} after the fixed routes; Axum prefers static segments, so /healthz still wins, but keep the /api prefix to avoid ambiguity.

Stand-in: the whole decision flow

Rust Create, follow and count links (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Extensions to try

  1. Custom aliases: accept an optional code; return 409 Conflict on a unique violation (see error handling with IntoResponse).
  2. Expiry: add expires_at and answer 410 Gone after it.
  3. Rate limit POST /api/links per IP (observability and hardening).
  4. Tests: write oneshot tests for create, redirect, 404 and invalid URL (testing handlers).
  5. Click analytics: insert a row per click into a second table instead of a counter, and aggregate in SQL.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a shortener usually answer with a temporary redirect (302/307) instead of 301?

    A cached permanent redirect bypasses your server, so you cannot count clicks or change the target.
  2. 2. Why validate that the target uses http or https?

    A redirect to an arbitrary scheme can run script or expose local resources.
  3. 3. What does UPDATE ... RETURNING target_url achieve in the redirect handler?

    One statement both increments the counter and returns the row, avoiding a read-then-write race.
  4. 4. How can a unique constraint help with random short codes?

    The database guarantees uniqueness even under concurrent requests; your code only needs to handle the error.

Summary

  • Plan routes and schema first; the shortener needs only one table.
  • Base 62 encoding turns an id into a compact code and back.
  • Validate input strictly: only http and https, with a host and a length limit.
  • Redirect with UPDATE ... RETURNING and a temporary status code.
  • Map failures to the right statuses: 422 invalid, 404 unknown, 409 conflict.
  • Extend it with aliases, expiry, rate limits and tests.

Next: Project: A Notes API with Authentication