Right now your shortener shortens anything it gets, and a body with no "url" even crashes it with a 500. Short links are clicked by strangers, so the app should check what it gets first. Bad input is turned away with 400 Bad Request, before anything is counted or stored.
Two tools do the checking. A dictionary's get(key, default) reads a key without crashing: when the key is missing, you get the default instead. A string's startswith method tells you whether it begins with a given text. Here is the same idea on another route, a list of tags that only accepts names starting with #:
@app.post("/tags")
def create_tag():
name = request.get_json().get("name", "")
if not name.startswith("#"):
return jsonify({"error": "A tag starts with #"}), 400
tags.append(name)
return jsonify({"name": name}), 201
Only addresses that start with http:// or https:// are web pages to send people to. Without that start, a browser reads www.python.org as a page of your own app, and ftp: or javascript: addresses don't belong behind a link strangers click. One more rule: the same URL sent twice gets the code it already has, with 200 OK, because nothing new was created. These are the test requests, in order:
POST /links {"url": "https://www.python.org/downloads/"} → 201 {"code": "1", "url": "https://www.python.org/downloads/"}
POST /links {"url": "ftp://files.example.com/report.pdf"} → 400 {"error": "The URL must start with http:// or https://"}
POST /links {"url": "javascript:alert(1)"} → 400 {"error": "The URL must start with http:// or https://"}
POST /links {"url": "www.python.org"} → 400 {"error": "The URL must start with http:// or https://"}
POST /links {} → 400 {"error": "The URL must start with http:// or https://"}
POST /links {"url": "http://example.com/old-page"} → 201 {"code": "2", "url": "http://example.com/old-page"}
POST /links {"url": "https://www.python.org/downloads/"} → 200 {"code": "1", "url": "https://www.python.org/downloads/"}
GET /links/3/stats → 404 {"error": "Link not found"}
GET /2 → 302 Location: http://example.com/old-page
Your task: in create_link, read the URL with get and the default "", and answer 400 with the error above when it starts with neither http:// nor https://. Then, before making a new code, look through links: if a stored link has the same URL, answer its code and URL with 200.
Assignment
Follow the Coding Tutorial to make create_link accept only real web addresses and give a URL it already knows its old code.
Hint
Both checks go above counter["last"] += 1, so a refused or repeated URL uses up no number: that is why GET /links/3/stats answers 404. A for loop over a dictionary gives its keys, here the codes.
Free plan: 30 tutor messages. PRO is unlimited.
