Start learning free

LESSON 169 OF 188 · 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. 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 with request.get_json() and answers 201 Created. For example, on another route:

@app.post("/notes")
def add_note():
    data = request.get_json()
    notes.append(data["text"])
    return jsonify({"text": data["text"]}), 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/"}
GET /check/codes  (the check calls your make_code)
  →  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 dictionary links and counter. Write make_code(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 make_code and the POST /links route.


Hint
Build the code from the back: each new character goes in front of code. Add 1 to counter["last"] before you make the code, and remember the , 201 after the JSON.


STEP 1 OF 12
    Ctrl + Enter to check