URL Shortener: Data and Serving
The data model is the set of records a service stores and the fields each record holds. This lesson designs the data model and the serving path, the fourth step of the method.
One record, three fields
One record holds the code, the long link, and the creation date. The printout shows the 3 fields of one stored record.
record = {"code": "qi", "long link": "https://example.com/a-very-long-article", "creation date": "2026-01-01"}
for field in ["code", "long link", "creation date"]:
print(field, ":", record[field])
print("fields in one record:", len(record))The redirect path, step by step
A redirect moves through arrival, lookup, and answer in that order. The printout shows the order for one known code.
store = {"qi": "https://example.com/a-very-long-article"}
def redirect(code):
print("step 1: request arrives for", code)
print("step 2: look up", code, "in the store")
print("step 3: answer 302 to", store[code])
redirect("qi")Known codes and unknown codes
A known code answers with a redirect to its long link. An unknown code answers 404, the not-found status.
store = {"qi": "https://example.com/a-very-long-article"}
def redirect(code):
if code in store:
return 302, store[code]
return 404, "not found"
print("qi:", redirect("qi"))
print("zz:", redirect("zz"))Example
store = {
"qi": "https://example.com/a-very-long-article",
"qj": "https://example.com/another-long-page",
"qk": "https://example.com/a-third-long-page",
}
visits = ["qi", "qj", "qi", "zz", "qk"]
hits = 0
misses = 0
for code in visits:
if code in store:
hits = hits + 1
print("visit", code, "-> 302 to", store[code])
else:
misses = misses + 1
print("visit", code, "-> 404 not found")
print("records stored:", len(store))
print("redirects:", hits)
print("not found:", misses)Key points
- Record: one stored item holding a short code, its long link, and its creation date.
- Key: the short code is the key, the value a lookup uses to find its record.
- Create path: a shorten call stores a new record and returns its short code.
- Redirect path: a redirect call finds the record by its code and answers with status 302.
- Not found: an unknown code answers with status 404 instead of a redirect.
- Store choice: a store organised by key fits, because every read asks for one code and nothing else.
In this example, 3 records are stored and 5 visits are served. 4 visits redirect to their long links and 1 visit answers not found, because its code has no record.
Note
the record is small and fixed in shape, so the store stays simple as records grow.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which value does a redirect lookup use to find its record?