Start learning free

LESSON 171 OF 173 · BACKEND: YOUR OWN API

Short Links: Count the Clicks in C#

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. Its values are text and numbers, so it is a Dictionary<string, object>, and a cast such as (int) reads a value back as a number. For example, with pages instead of links:

var pages = new Dictionary<string, Dictionary<string, object>>();
pages["home"] = new Dictionary<string, object> { ["title"] = "Home", ["views"] = 0 };
pages["home"]["views"] = (int)pages["home"]["views"] + 1;
Console.WriteLine(pages["home"]["views"]);   // 1

Count the click in the /{code} route 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: the starting code already declares links as a Dictionary<string, Dictionary<string, object>>; it doesn't compile until the /{code} route returns on every path again. In the POST /links route, store each link as a dictionary with its "url" and its "clicks", starting at 0. In the /{code} route, 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 GET /links/{code}/stats route.


Hint
links[code] is a dictionary now, so the URL is one level deeper, under the key "url". Its values are objects: (int) and (string) read them as a number and as text. Add 1 to the clicks before the return.


STEP 1 OF 8
    Ctrl + Enter to check

    Own Links Stats in C#

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