Start learning free

LESSON 171 OF 188 · BACKEND: YOUR OWN API

Short Links: Count the Clicks

Practice

Whoever shares a short link wants to know how many people opened it. Every visit through the short link is a click, so each link must now remember two things: its URL and its number of clicks.

A dictionary of dictionaries: the value stored under each code becomes a small dictionary of its own, and two pairs of brackets reach inside it. For example, with pages instead of links:

pages = {"home": {"title": "Home", "views": 0}}
pages["home"]["views"] += 1
print(pages["home"])   # {'title': 'Home', 'views': 1}

Count the click in follow_link before its return, since nothing after a return runs. Then a new route, GET /links/<code>/stats, answers a link's numbers. Looking at the stats is not a click.

After three POST /links made the codes 1, 2 and 3, and the visits GET /1, GET /1 and GET /2 (each still answers 302 to its URL), your app must answer:

GET /links/1/stats  →  200  {"code": "1", "url": "https://www.python.org/downloads/", "clicks": 2}
GET /links/2/stats  →  200  {"code": "2", "url": "https://en.wikipedia.org/wiki/URL_shortening", "clicks": 1}
GET /links/3/stats  →  200  {"code": "3", "url": "https://flask.palletsprojects.com/en/stable/quickstart/", "clicks": 0}
GET /links/4/stats  →  404  {"error": "Link not found"}

Your task: in create_link, store each link as a dictionary with its "url" and its "clicks", starting at 0. In follow_link, count the click, then redirect to the link's URL. At the end of the file, add GET /links/<code>/stats, with the same 404 for unknown codes.


Assignment
Follow the Coding Tutorial to count the clicks and add the link_stats route.


Hint
links[code] is a dictionary now, so the URL is one level deeper, under the key "url". Add 1 to the clicks before the return.


STEP 1 OF 9
    Ctrl + Enter to check