A shop's front page often shows a menu of its categories. The shop keeps no list of them: each product only knows its own category. So your API builds the list from the products, every time someone asks.
The list must be distinct: two products are in "office", but the menu shows it once. Before adding a value to a list, not in tells you whether the list already holds it. Then sorted puts a list of strings in alphabetical order, with no key function. The same idea on a list of colors:
colors = []
for color in ["red", "blue", "red"]:
if color not in colors:
colors.append(color)
print(sorted(colors)) # ['blue', 'red']
The list is built from the products on every request, so it always follows them. A product in a new category adds that category, and deleting the only product of a category removes it. Your code must answer these requests, in this order:
GET /categories → 200 ["home", "kitchen", "office"]
POST /products {"name": "Chair", "price": 45, "category": "furniture"} → 201 {"id": 5, "name": "Chair", …}
POST /products {"name": "Stapler", "price": 9, "category": "office"} → 201 {"id": 6, "name": "Stapler", …}
GET /categories → 200 ["furniture", "home", "kitchen", "office"]
DELETE /products/3 → 204
GET /categories → 200 ["furniture", "kitchen", "office"]
Your task: add a route for GET /categories that answers the distinct categories of the products, in alphabetical order, as a JSON list.
Assignment
Follow the Coding Tutorial to build the GET /categories route: an empty list, a loop over products, a not in check, and a sorted answer.
Hint
Append a category only when it is not in the list yet. A list of strings needs no key function: sorted(categories) puts it in alphabetical order.
Free plan: 30 tutor messages. PRO is unlimited.
