Start learning free

LESSON 171 OF 173 · BACKEND: YOUR OWN API

Short Links: Count the Clicks in Java

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 map of maps: the value stored under each code becomes a small map of its own, and two gets reach inside it. Map.of can't change later, so copy it into a new HashMap<>(...), which can. For example, with pages instead of links:

Map<String, Map<String, Object>> pages = new HashMap<>();
pages.put("home", new HashMap<>(Map.of("title", "Home", "views", 0)));
pages.get("home").put("views", (int) pages.get("home").get("views") + 1);
System.out.println(pages.get("home").get("views"));   // 1

Count the click in followLink before its return: Java won't even compile a line after a return. Then a new mapping, 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: the starting code already declares links as Map<String, Map<String, Object>>, so it doesn't compile until the old lines are updated. In createLink, store each link as a map with its "url" and its "clicks", starting at 0. In followLink, count the click, then redirect to the link's URL. At the end of LinkController, add GET /links/{code}/stats, with the same 404 for unknown codes.


Assignment
Follow the Coding Tutorial to count the clicks and add the linkStats method.


Hint
links.get(code) is a map now, so the URL is one level deeper, under the key "url"; (String) reads it as text and (int) reads the clicks as a number. Add 1 to the clicks before the return.


STEP 1 OF 9
    Ctrl + Enter to check

    Own Links Stats in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free