A real shop can have thousands of products, and a page often shows only a few. A client asks for that with a query parameter: ?limit=2 means "at most 2 products".
To keep the first few items of a list, use a slice. items[:n] goes from the start up to, but not including, position n. If n is bigger than the list, you simply get the whole list.
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[:2]) # ['Mon', 'Tue']
print(days[:10]) # the whole list, no error
Cut the list last, after filtering and sorting, so ?sort=price&limit=2 gives the two cheapest products. A limit of 0 or less makes no sense, so it gets 400. Without limit, the answer is the whole list, as before. The lists below show product names only.
GET /products?limit=2 → 200 [Mug, Notebook]
GET /products?sort=price&limit=2 → 200 [Pen, Notebook]
GET /products?category=office&limit=1 → 200 [Notebook]
GET /products?limit=10 → 200 [Mug, Notebook, Lamp, Pen]
GET /products?limit=0 → 400 {"error": "Limit must be 1 or more"}
GET /products?limit=-3 → 400 {"error": "Limit must be 1 or more"}
Your task: in GET /products, read limit as a whole number, answer 400 when it is less than 1, and cut the list to its first limit products.
Assignment
Follow the Coding Tutorial to add a limit to GET /products.
Hint
Read limit with type=int, like max_price. Check it before the loop, and slice result just before the return, after the sorting.
Free plan: 30 tutor messages. PRO is unlimited.
