Start learning free

LESSON 169 OF 173 · BACKEND: YOUR OWN API

Short Links: Create in C#

Practice

A new project starts here: a link shortener. It gives each long URL a short code and remembers the pair. Later, whoever opens the code is sent on to the long URL. You will build it over five lessons, starting now.

Codes in base 36: codes count like numbers, 1, 2, 3…, but with 36 characters instead of 10: after 9 come a, b, … z, and only then 10. As in base 10, % 36 gives the last digit and / 36 drops it (dividing two ints drops the remainder). For example, 100 = 2 × 36 + 28, and the character for 28 is s, so 100 is written "2s".

Creating with POST: a route that stores something new uses POST, takes the JSON body as a JsonElement and answers 201 Created. For example, on another route:

app.MapPost("/notes", (JsonElement data) => {
    var text = data.GetProperty("text").GetString();
    notes.Add(text);
    return Results.Json(new { text = text }, statusCode: 201);
});

Your app must give these answers, in this order:

POST /links  {"url": "https://www.python.org/downloads/"}
  →  201  {"code": "1", "url": "https://www.python.org/downloads/"}
POST /links  {"url": "https://en.wikipedia.org/wiki/URL_shortening"}
  →  201  {"code": "2", "url": "https://en.wikipedia.org/wiki/URL_shortening"}
POST /links  {"url": "https://flask.palletsprojects.com/en/stable/quickstart/"}
  →  201  {"code": "3", "url": "https://flask.palletsprojects.com/en/stable/quickstart/"}
…  six more POST /links get the codes "4" to "9"
POST /links  {"url": "https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST"}
  →  201  {"code": "a", "url": "https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST"}

Your task: the starting code already has digits, the dictionary links and counter. Write the local function MakeCode(int number), which turns a number into its base-36 code: 10 gives "a", 36 gives "10", 1296 gives "100". Then write POST /links: it gives the URL the next code, stores the pair in links and answers 201 with the code and the URL.


Assignment
Follow the Coding Tutorial to write MakeCode and the POST /links route.


Hint
Build the code from the back: each new character goes in front of code. Add 1 to counter before you make the code, and pass statusCode: 201 to Results.Json. C# won't compile MakeCode until it returns something, so the app only runs again once you reach its return.


STEP 1 OF 11
    Ctrl + Enter to check

    Own Links Create 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