Sub topic 3
Designing the API
This chapter defines the HTTP interface of the URL shortener: which endpoints exist, what they accept and return, and which status codes they use. It assumes you know HTTP methods, status codes, and headers, and can read short Python programs. The requirements and capacity chapters established the scope: create a short link, redirect to the original URL, and optionally support aliases and expiry. The API turns that scope into a contract.
Two surfaces with different needs
A URL shortener exposes two kinds of traffic, and they should be designed separately.
- Management API. Clients create, inspect, and delete links. It is low volume and needs authentication, validation, and JSON bodies.
- Redirect path. Browsers request
GET /{short_code}. It is very high volume, has no body, and must be as fast as possible.
The capacity estimates showed a read-heavy workload, often 100 redirects for every link created. So the redirect route should do as little as possible. It skips JSON parsing and authentication, and later chapters put a cache in front of it. Keeping the two surfaces on different path prefixes (/api/v1/... versus /{code}) lets you route, rate limit, and scale them independently.
Endpoints
| Method and path | Purpose | Success | Common errors |
|---|---|---|---|
| `POST /api/v1/links` | Create a short link | 201 Created | 400, 401, 409, 429 |
| `GET /api/v1/links/{code}` | Read link metadata | 200 OK | 401, 404 |
| `DELETE /api/v1/links/{code}` | Remove a link | 204 No Content | 401, 404 |
| `GET /{code}` | Redirect to the long URL | 301 or 302 | 404, 410 |
Some design choices in this table need explaining.
- Version the management API. The
/v1/prefix lets you change request shapes later without breaking existing clients. Short links themselves must never change, because they are printed on posters and embedded in documents. - Use nouns for resources. The resource is a link, so create it with
POSTto the collection. Avoid paths like/api/createShortUrl. - Do not offer
PUTorPATCHon the long URL at first. Changing a destination invalidates caches and complicates analytics. If you need it later, add it deliberately.
Creating a link
A request needs one required field and two optional ones:
POST /api/v1/links HTTP/1.1
Host: short.example
Content-Type: application/json
Authorization: Bearer <api-key>
{
"long_url": "https://example.com/articles/2026/very-long-title?ref=newsletter",
"custom_alias": "spring-sale",
"expires_at": "2027-01-31T23:59:59Z"
}A successful response uses 201 Created, which means a new resource now exists. It includes a Location header pointing at the new resource and a body with everything the client needs:
{
"short_code": "spring-sale",
"short_url": "https://short.example/spring-sale",
"long_url": "https://example.com/articles/2026/very-long-title?ref=newsletter",
"expires_at": "2027-01-31T23:59:59Z"
}Return the full short_url and not only the code. Clients should not have to know how to assemble it, and the base domain can then change without client changes.
Validation rules
The create endpoint is a trust boundary, so validate every field.
long_urlmust be a string of bounded length (2,048 characters is a common cap). It must parse with anhttporhttpsscheme and a host. Rejectjavascript:,data:, andfile:URLs, which can turn a short link into an attack vector.custom_aliasmust match a strict pattern, for example 4 to 10 characters from[0-9A-Za-z]. It must not collide with reserved names such asapiorhealth, which would shadow your own routes.expires_atmust be a timezone-aware ISO 8601 timestamp in the future.
Idempotency and duplicate URLs
If a client retries a POST after a network timeout, should it get a second short code? There are two reasonable policies.
- Always create a new link. This is simple, and each link can have its own owner, expiry, and analytics. Duplicates are cheap, since a row is a few hundred bytes.
- Return the existing link for the same long URL. This saves space but breaks down quickly. Different users want separate analytics, and different expiry settings make two links for one URL distinct.
Most designs choose the first policy. To make retries safe, accept an optional Idempotency-Key header. The server stores the key with the response for a short period and replays that response if the same key arrives again.
Error responses
Use one consistent error body so clients can handle failures in one place:
{
"error": "alias_taken",
"message": "The alias 'spring-sale' is already in use."
}The error field is a stable machine-readable string. The message field is for humans and may change.
| Status | When to use it |
|---|---|
| 400 Bad Request | Malformed JSON, invalid URL, bad alias format, expiry in the past |
| 401 Unauthorized | Missing or invalid API key |
| 404 Not Found | Short code does not exist |
| 409 Conflict | Custom alias already taken |
| 410 Gone | Link existed but has expired or was deleted |
| 429 Too Many Requests | Rate limit exceeded; include a `Retry-After` header |
The difference between 404 and 410 matters on the redirect path. A 410 tells crawlers and monitors that the link was valid once and is intentionally gone. A 404 says it never existed. If you hard-delete expired rows, you lose this distinction, so some systems keep a small tombstone record.
The redirect route
GET /{code} returns a redirect status and a Location header, with an empty or tiny body. The next chapters cover the trade-offs of 301 versus 302. For now, the API contract only needs to decide that this route is separate, public, unauthenticated, and read-only. It must never modify state synchronously, because a slow write would add latency to every click. Analytics events should be sent to a queue instead.
A runnable sketch
This Flask program implements the contract with an in-memory dictionary and a counter. Install Flask with pip install flask. It is not production code, since it has no authentication, persistence, or locking. It does show where each rule lives.
import re
from datetime import datetime, timezone
from urllib.parse import urlparse
from flask import Flask, jsonify, redirect, request
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
ALIAS_RE = re.compile(r"[0-9A-Za-z]{4,10}")
RESERVED = {"api", "health"}
app = Flask(__name__)
LINKS = {}
next_id = 1_000_000
def encode(n: int) -> str:
if n == 0:
return ALPHABET[0]
digits = []
while n > 0:
n, r = divmod(n, 62)
digits.append(ALPHABET[r])
return "".join(reversed(digits))
def valid_url(value) -> bool:
if not isinstance(value, str) or len(value) > 2048:
return False
parts = urlparse(value)
return parts.scheme in ("http", "https") and bool(parts.netloc)
def error(status: int, code: str, message: str):
return jsonify(error=code, message=message), status
@app.post("/api/v1/links")
def create_link():
global next_id
body = request.get_json(silent=True)
if not isinstance(body, dict):
return error(400, "invalid_body", "Body must be a JSON object.")
long_url = body.get("long_url")
if not valid_url(long_url):
return error(400, "invalid_url", "long_url must be an http or https URL.")
expires_at = None
raw_expiry = body.get("expires_at")
if raw_expiry is not None:
try:
expires_at = datetime.fromisoformat(raw_expiry)
except (TypeError, ValueError):
return error(400, "invalid_expiry", "expires_at must be ISO 8601.")
if expires_at.tzinfo is None or expires_at <= datetime.now(timezone.utc):
return error(400, "invalid_expiry", "expires_at must be a future time with a timezone.")
alias = body.get("custom_alias")
if alias is not None:
if (not isinstance(alias, str) or not ALIAS_RE.fullmatch(alias)
or alias in RESERVED):
return error(400, "invalid_alias", "Alias must be 4-10 letters or digits.")
if alias in LINKS:
return error(409, "alias_taken", f"The alias '{alias}' is already in use.")
code = alias
else:
code = encode(next_id)
next_id += 1
LINKS[code] = {"long_url": long_url, "expires_at": expires_at}
short_url = request.host_url + code
response = jsonify(
short_code=code,
short_url=short_url,
long_url=long_url,
expires_at=raw_expiry,
)
response.status_code = 201
response.headers["Location"] = short_url
return response
@app.get("/<code>")
def follow(code):
link = LINKS.get(code)
if link is None:
return error(404, "not_found", "No such link.")
expiry = link["expires_at"]
if expiry is not None and expiry <= datetime.now(timezone.utc):
return error(410, "expired", "This link has expired.")
return redirect(link["long_url"], code=302)
if __name__ == "__main__":
app.run(port=5000)Test it with two commands in a second terminal:
curl -i -X POST http://localhost:5000/api/v1/links \
-H "Content-Type: application/json" \
-d '{"long_url": "https://example.com/some/long/path"}'
curl -i http://localhost:5000/4c92The first call returns 201 and a code derived from the counter. Use that code in the second call, which should return 302 with a Location header.
Common mistakes
- Letting aliases shadow routes. Without the reserved list, a user who registers
apicreates an ambiguity at the router. - Not validating schemes. Accepting any string as
long_urlallowsjavascript:links and open redirects to internal hosts. - Returning 200 with an error body. Monitoring and clients rely on status codes. Use them accurately.
- Doing writes on the redirect path. Counting clicks in the request handler turns a cheap read into a write and caps your throughput.
- Exposing sequential codes without thought. A counter-based code like the one in the sketch can be enumerated by anyone who tries adjacent values. The abuse chapter covers mitigations.
- Forgetting pagination. If you later add
GET /api/v1/linksto list a user's links, add cursor-based pagination from the start.
Exercise
A client sends POST /api/v1/links with a custom_alias that is already used by another link, and the request is otherwise valid. Which status code should the server return, and why not 400?
Show answer
Return 409 Conflict. The request is syntactically and semantically valid, but it conflicts with the current state of the system. A distinct status and an error code such as "alias_taken" let clients respond specifically, for example by offering alternative aliases. A 400 should be reserved for requests that are malformed or break validation rules regardless of server state.
Exercise
Why should the redirect route GET /{code} avoid synchronously writing a click counter to the database, and what should it do instead?
Show answer
A synchronous write adds database latency to every redirect and turns a read-heavy path into a write-heavy one, which limits throughput and hurts availability if the write store is slow. Instead, the handler should return the redirect immediately and publish a small click event to a queue or log, to be processed asynchronously by an analytics worker.