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

Core Entities & RelationshipsURL (Main Entity)Fields:short_code: String (PK)long_url: Stringcreated_at: Timestampexpires_at: Timestampuser_id: String (optional)custom_alias: Booleanclick_count: IntegerUser (Optional)Fields:user_id: String (PK)email: Stringapi_key: Stringcreated_at: TimestampAnalyticsFields:click_id: String (PK)short_code: String (FK)timestamp: Timestampip_address: StringownstracksDatabase ChoiceNoSQL (DynamoDB)✓ Simple key-value✓ Easy sharding✓ Fast lookups✓ Auto-scaling✗ No complex queriesSQL (PostgreSQL)✓ ACID guarantees✓ Complex queries✓ Relationships✗ Harder to shard✗ Scaling complexity

✅ 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 API

Request:

{
"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 API

Request:

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 2

Request:

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