Start learning free

LESSON 169 OF 173 · BACKEND: YOUR OWN API

Short Links: Create

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 method that stores something new uses POST, reads the JSON body with @RequestBody and answers 201 Created. For example, on another route:

@PostMapping("/notes")
Object addNote(@RequestBody Map<String, Object> data) {
    notes.add((String) data.get("text"));
    return ResponseEntity.status(201).body(Map.of("text", data.get("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/"}
… the next six POSTs get the codes "4" to "9", then:
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 LinkController already has DIGITS, the map links and counter. Write makeCode(int 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 createLink method for POST /links.


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 answer with ResponseEntity.status(201). Java compiles the file only once every method that promises a value has its return.


STEP 1 OF 12
    Ctrl + Enter to check