Start learning free

LESSON 170 OF 173 · 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 mapping like @GetMapping("/{code}") takes any text between the slashes, and @PathVariable String code hands it to the method as a String. That suits codes made of digits and letters.

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

@GetMapping("/docs")
Object docs() {
    return ResponseEntity.status(302).header("Location", "https://spring.io/guides").build();
}

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 LinkController, add GET /{code}. When the code isn't in links, answer 404 with {"error": "Link not found"}; otherwise answer 302 with Location set to the stored URL. GetMapping and PathVariable are already imported at the top.


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


Hint
The parameter has the same name as the part in curly braces. Check for a missing code first and return the 404; only then read links.get(code). Java wants a return on every path, so the file compiles only once both returns are there.


STEP 1 OF 5
    Ctrl + Enter to check