Skip to content

Level 3: RESTful URL Shortener API (Web Servers & Database Design)

Welcome to the third level! You will now build a fully functioning backend REST API.

In Python, you might use Flask or FastAPI. In Go, the standard library net/http package is extremely powerful, fast, and feature-rich. In Go 1.22+, net/http.ServeMux got a major upgrade, adding path parameter matching (like /{code}) and HTTP method restrictions directly in the routing patterns!

API Specification

You must implement the following endpoints:

  1. Shorten a URL (POST /shorten):
  2. Request Body: {"url": "https://example.com/very/long/path"}
  3. Response: {"short_code": "a1b2c", "short_url": "http://localhost:8080/a1b2c"}
  4. Behavior: Generate a unique short code, save the mapping, and return a HTTP 201 Created status.
  5. Redirect to Original URL (GET /{short_code}):
  6. Behavior: Look up the short code. If found, increment its hit counter and redirect using HTTP status 307 Temporary Redirect. If not found, return HTTP 404 Not Found.
  7. Get Metrics (GET /metrics/{short_code}):
  8. Response: {"short_code": "a1b2c", "original_url": "https://example.com/very/long/path", "hits": 12}

Clean Architecture & Dependency Injection

One of the key patterns you will learn in this project is clean architecture using interfaces. We will decouple our HTTP layer from our storage engine by using an interface URLStore.

graph TD
    HTTP["HTTP Handler"] -->|Uses| StoreInterface["URLStore Interface"]
    StoreInterface -->|Implemented by| MemoryStore["In-Memory Map Store"]
    StoreInterface -->|Implemented by| SQLStore["SQLite / PostgreSQL Store"]

This allows us to: * Test our HTTP handlers easily by passing in a dummy/mock store. * Change our database backend (from In-Memory to Postgres/SQLite) without altering a single line of HTTP controller logic.


Getting Started

  1. Look at store.go which defines the URLStore interface, its metrics struct, and the in-memory map implementation skeleton.
  2. Look at handlers.go which contains the HTTP handler skeleton.
  3. Look at handlers_test.go which contains API tests using Go's httptest package.
  4. Run the tests:
    /usr/local/go/bin/go test -v ./level3_url_shortener/...
    
  5. Implement the store and handlers.