Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 50 ยท Projects

Project: URL shortener

Build a URL shortener with FastAPI and SQLite: generate short codes, accept custom aliases, redirect, count clicks, validate URLs and return 409 on conflicts.

A URL shortener turns https://example.com/some/very/long/path?with=parameters into something like https://sho.rt/a1B2c3. It is a classic project because it is small, yet it touches real API design questions: how do you generate codes that never collide, what should happen when someone asks for a name that is taken, which redirect status is right, and how do you count visits correctly?

You will build it with FastAPI, Pydantic validation and SQLAlchemy on an in-memory SQLite database, in the style of SQLAlchemy with FastAPI. The app runs right here in your browser.

The plan

The API has three endpoints. Notice that the redirect lives at the root of the site (/a1B2c3), because a short link has to be as short as possible.

Method and path Purpose Success Errors
POST /links Create a short link, optionally with a custom alias 201 + link 409 alias taken, 422 invalid URL or alias
GET /{code} Redirect to the original URL and count the click 307 redirect 404 unknown code
GET /links/{code} Show statistics 200 + link 404

What happens to a link

Create Validate the URL, pick a code.
Share People open /code.
Redirect Send the browser to the target.
Count Add one click per visit.
1 / 2

Generating short codes

The simplest idea is to use the database id as the code, written in a compact alphabet. Base 62 (digits, lowercase and uppercase letters) packs numbers tightly: six characters cover more than 56 billion links. Two problems remain. Sequential codes (000001, 000002, ...) reveal how many links exist and are trivial to guess. And random codes need a collision check against the database.

A neat middle path is to scramble the id with a reversible formula: multiply it by a large odd number that shares no factor with 62**6, and keep the remainder. Because the multiplier is coprime with the modulus, different ids can never give the same result (the mapping is a bijection), yet the codes look random. The output is deterministic, which also makes tests easy.

Python Base 62 codes, scrambled ids and URL validation

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 input()), it gets the next line from this box.

All 20,000 ids produced different codes, and the formula never needs a database lookup to stay unique. Validation is a security matter here, not only tidiness: HttpUrl accepts only http and https, so a link such as javascript:alert(1) can never become a redirect target. Notice also that Pydantic normalizes the URL (a bare host gets a trailing slash).

There is still one collision possible: a user may pick a custom alias that equals a code we would generate later. The app below handles that by checking the database and trying the next candidate.

Redirects, status codes and counting clicks

Which redirect status? 301 Moved Permanently tells browsers to remember the answer and skip your server next time, so clicks stop being counted and you could never change the target. 302 and 307 mean "temporary", so every visit reaches you. FastAPI's RedirectResponse uses 307 by default. It also tells clients to repeat the same method, which is the safest choice. Use it when you want statistics.

Counting needs care too. Reading the number, adding one in Python and writing it back loses clicks when two visits overlap. Let the database do the arithmetic in one statement: UPDATE links SET clicks = clicks + 1 WHERE code = ?.

Finally, a route order detail (Path parameters): GET /{code} matches any single-segment path, so the specific routes such as /links/{code} must stay clearly separate, and links itself is on a reserved list that aliases cannot use.

The complete app

Here is the whole service. create_app() builds a new app on a new database each time, which the checks at the end use. Conflicts are caught from the database itself: the UNIQUE constraint on code is the real guarantee, so even two simultaneous requests cannot create the same alias. The handler catches IntegrityError, rolls back and answers 409 (see Status codes and error handling).

Python The URL shortener service, with checks

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 input()), it gets the next line from this box.

Walk through the output. The created link has a generated six-character code, and short_url is built with request.url_for("follow", ...), so it always matches the host the client used (behind a proxy, configure trusted forwarded headers as described in Deployment). The second alias request is answered with 409, three visits are counted, and the last lines prove that a custom alias cannot block a later generated code.

Ideas to extend it

  1. Expiry. Add an expires_at column and answer 410 Gone after it passes.
  2. Rate limiting. Anonymous creation is abuse-prone; see API keys and security practices.
  3. Per-visit analytics. Store one row per click (time, referrer) in a second table instead of a single counter, and aggregate it for the stats endpoint.
  4. Blocklist. Reject targets that point to your own domain, which would create redirect loops, and malicious hosts.
  5. Swap the database. The code only uses the SQLAlchemy session, so PostgreSQL is a matter of changing the engine URL and adding migrations.
  6. Cache hot links. Redirects are read far more often than links are created, which suits the TTL cache from Performance and caching. Remember that cached hits would skip the click counter unless you count them separately.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the app answer 409 for a taken alias instead of 400 or 422?

    The body is well formed, so it is not a validation error. The alias exists already, which is a conflict with existing data.
  2. 2. Why is clicks = clicks + 1 done inside a single UPDATE statement?

    The database applies the increment atomically. Doing it in Python could overwrite a concurrent update.
  3. 3. Which redirect status keeps every visit reaching your server so clicks can be counted?

    Temporary redirects (302, 307) are not cached as permanent by browsers, so each visit calls your server. Permanent ones may be remembered and skip it.
  4. 4. What is the main reason to validate the URL with HttpUrl?

    HttpUrl checks the format and the scheme. It does not contact the site.

Summary

  • Derive short codes from the primary key: base 62 keeps them compact, and a coprime multiplier scrambles them without collisions.
  • Let the UNIQUE constraint guarantee uniqueness and translate IntegrityError into 409 Conflict.
  • Validate input at the edge: HttpUrl for targets, a regex and a reserved list for aliases.
  • Use RedirectResponse (307 by default) for statistics-friendly redirects, and increment counters in SQL.
  • Keep the catch-all /{code} route in mind: reserve names and keep specific routes distinct.

Last project of the course: a Blog API with authentication.