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:
- Shorten a URL (
POST /shorten): - Request Body:
{"url": "https://example.com/very/long/path"} - Response:
{"short_code": "a1b2c", "short_url": "http://localhost:8080/a1b2c"} - Behavior: Generate a unique short code, save the mapping, and return a HTTP
201 Createdstatus. - Redirect to Original URL (
GET /{short_code}): - Behavior: Look up the short code. If found, increment its hit counter and redirect using HTTP status
307 Temporary Redirect. If not found, return HTTP404 Not Found. - Get Metrics (
GET /metrics/{short_code}): - 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¶
- Look at store.go which defines the
URLStoreinterface, its metrics struct, and the in-memory map implementation skeleton. - Look at handlers.go which contains the HTTP handler skeleton.
- Look at handlers_test.go which contains API tests using Go's
httptestpackage. - Run the tests:
- Implement the store and handlers.