URL Shortener - Step 2: API Design & Core Entities
Step 2 of 6: A - API Design & Core Entities
Define the data model and API contracts before building
✅ Decision 1: NoSQL
Simple key-value access pattern
Perfect for short_code → URL lookup
✅ Decision 2: Short Code as PK
Natural sharding key
O(1) lookups guaranteed
✅ Decision 3: Separate Analytics
Don't slow down redirects
Async write to analytics DB
🔌 REST API Endpoints
POST /api/shorten
Core APIRequest:
{
"long_url": "https://example.com/very/long/url",
"custom_alias": "my-link", // optional
"expires_at": "2034-01-01" // optional
}
Response (201):
{
"short_url": "https://short.ly/abc123",
"short_code": "abc123",
"created_at": "2024-01-01T12:00:00Z"
}
GET /{short_code}
Core APIRequest:
GET /abc123
No body required
Response (302):
HTTP/1.1 302 Found
Location: https://example.com/very/long/url
Cache-Control: no-cache
// Browser redirects automatically
GET /api/stats/{short_code}
Phase 2Request:
GET /api/stats/abc123
Requires authentication
Response (200):
{
"total_clicks": 1234,
"unique_visitors": 890,
"last_clicked": "2024-01-01T12:00:00Z"
}
🗄️ Data Access Patterns
Write Pattern
1.Generate unique short_code
2.Check for collision (rare)
3.INSERT into URL table
4.Return short URL
Read Pattern
1.Extract short_code from URL
2.GET by primary key (O(1))
3.Return 302 redirect
4.Async: log analytics
💡 What We've Defined
Data Model
Simple URL entity with NoSQL for easy scaling
API Contract
Two core endpoints: create & redirect
Access Patterns
Optimized for key-value lookups