Start learning free

LESSON 170 OF 188 · BACKEND: YOUR OWN API

Short Links: Redirect

Practice

The app stores short links, but a short link is only useful if opening it takes you to the long URL. A short link is the app's address, a slash, then the code: /1, /zz.

Any text in the path: a route like "/<code>", with no converter such as int:, takes any text between the slashes and hands it to the function as a string. That suits codes made of digits and letters.

Redirects: redirect(url) makes an answer with the status 302 Found and a Location header set to the URL. The answer has no page of its own: a browser that gets it opens that URL right away. For example, on another route:

@app.get("/docs")
def docs():
    return redirect("https://flask.palletsprojects.com/")

After two POST /links made the codes 1 and 2, your app must answer:

GET /1   →  302  Location: https://www.python.org/downloads/
GET /2   →  302  Location: https://en.wikipedia.org/wiki/URL_shortening
GET /3   →  404  {"error": "Link not found"}
GET /zz  →  404  {"error": "Link not found"}

And once a third POST /links made the code 3:

GET /3   →  302  Location: https://flask.palletsprojects.com/en/stable/quickstart/

Your task: at the end of the file, add GET /<code>. When the code isn't in links, answer 404 with {"error": "Link not found"}; otherwise redirect to the stored URL. redirect is already imported at the top.


Assignment
Follow the Coding Tutorial to add the follow_link route that sends a short link on to its long URL.


Hint
The function's parameter has the same name as the part in angle brackets. Check for a missing code first and return the 404; only then read links[code].


STEP 1 OF 5
    Ctrl + Enter to check