Start learning free

LESSON 169 OF 173 · BACKEND: YOUR OWN API

Short Links: Create in JavaScript

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 dividing by 36 and rounding down with Math.floor drops it. 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, reads the JSON body from req.body and answers 201 Created. For example, on another route:

app.post("/notes", (req, res) => {
  const data = req.body;
  notes.push(data.text);
  res.status(201).json({ text: data.text });
});

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/"}
GET /check/codes  (the check calls your makeCode)
  →  1 → "1", 9 → "9", 10 → "a", 35 → "z", 36 → "10", 37 → "11", 1295 → "zz", 1296 → "100"

Your task: the starting code already has DIGITS, the object links and the counter lastNumber. Write makeCode(number), which turns a number into its base-36 code. 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 lastNumber before you make the code, and remember res.status(201) before .json(...).


STEP 1 OF 11
    Ctrl + Enter to check

    Own Links Create in JavaScript

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