Sub topic 3
Designing the API
This chapter assumes you know basic HTTP (methods, status codes, headers) and can read simple Python. It turns the requirements from the earlier chapters into a concrete API. Code generation and storage come later, so here the service is a black box with two jobs: create a short link and resolve one.
Two operations, two different paths
The read-heavy workload gives the API an asymmetry. Creating links is rare. Resolving them is constant. So the two paths get different shapes.
| Operation | Method and path | Success | Typical errors |
|---|---|---|---|
| Create a short link | `POST /api/v1/urls` | `201 Created` | 400, 401, 409, 429 |
| Resolve a short link | `GET /{short_code}` | `301` or `302` | 404, 410 |
| Delete a link (optional) | `DELETE /api/v1/urls/{short_code}` | `204 No Content` | 401, 404 |
The resolve path sits at the root, with no /api prefix, so the public short URL stays as short as possible. It also returns a redirect, not JSON, because browsers follow it directly.
Creating a link
The request carries the long URL. The alias and expiry are optional, and later chapters cover how they work.
{
"long_url": "https://example.com/articles/2026/very-long-title?ref=newsletter",
"custom_alias": "spring-sale",
"expires_at": "2027-01-01T00:00:00Z"
}A successful response returns the new resource and points to it in the Location header:
{
"short_code": "spring-sale",
"short_url": "https://sho.rt/spring-sale",
"long_url": "https://example.com/articles/2026/very-long-title?ref=newsletter",
"expires_at": "2027-01-01T00:00:00Z"
}Use POST, not PUT. The client does not choose the resource's identity unless it supplies an alias, and the server normally assigns the code.
Choosing status codes
Precise status codes let clients react without parsing error text.
400 Bad Request: the URL is malformed or uses a disallowed scheme.401 Unauthorized: the API key is missing or invalid.409 Conflict: the custom alias is already taken.404 Not Found: the short code never existed.410 Gone: the code existed but has expired or been deleted.429 Too Many Requests: the caller exceeded a rate limit. Include aRetry-Afterheader.
The 404 and 410 split costs little and helps debugging, but it means you must keep expired rows long enough to answer 410.
Validating input at the boundary
The API is a trust boundary, so validate before anything touches storage. Accept only http and https. Schemes such as javascript: or file: turn a shortener into an attack tool.
from urllib.parse import urlparse
MAX_URL_LENGTH = 2048
def validate_long_url(url: str) -> bool:
if len(url) > MAX_URL_LENGTH:
return False
parts = urlparse(url)
return parts.scheme in ("http", "https") and bool(parts.netloc)
print(validate_long_url("https://example.com/a?b=1")) # True
print(validate_long_url("javascript:alert(1)")) # False
print(validate_long_url("https:///no-host")) # FalseIdempotency and duplicates
Decide what happens when the same long URL is submitted twice. There are two options:
- Return a new code each time. This is simple. Each caller gets an independent link, which matters if their expiry or analytics differ.
- Return the existing code. This saves storage, but it needs a lookup on the long URL and mixes ownership between users.
Most designs choose the first. If clients retry after a timeout, accept an Idempotency-Key header so a retry does not create a second link.
The full flow
Exercise
A user requests a custom alias that another user already owns. Which status code should the API return, and why not 400?
Show answer
Return 409 Conflict. The request is well formed, so 400 would be misleading. It fails because it conflicts with the current state of the system, and the client can fix it by choosing a different alias.