Start learning free

LESSON 33 OF 188 · BACKEND: YOUR FIRST API

Reviews for a Product

Practice

Customers can now review a product: a number of stars from 1 to 5 and a short text. A review belongs to one product, so its path goes under the product's path: /products/1/reviews are the reviews of product 1. This is a nested path, and the id in the middle is a path parameter, as in GET /products/1.

The reviews are already in the file, in the dictionary reviews: each key is a product id, and each value is the list of that product's reviews. A product with no reviews has no key, so reviews.get(product_id, []) gives its list, or an empty one. The same dictionary of lists, with other values:

tags = {1: ["sale", "new"]}
print(tags.get(1, []))   # ['sale', 'new']
print(tags.get(2, []))   # []
tags[2] = tags.get(2, []) + ["gift"]
print(tags[2])           # ['gift']

One path can have a route for each method: GET reads a product's reviews, and POST adds one and answers 201 with it. Both answer 404 when no product has the id. Your code must answer these requests, in this order:

GET /products/1/reviews  →  200  [{"stars": 5, "text": "Great mug"}, {"stars": 4, "text": "A bit small"}]
GET /products/4/reviews  →  200  []
GET /products/99/reviews  →  404  {"error": "Product not found"}
POST /products/2/reviews  {"stars": 4, "text": "Nice paper"}  →  201  {"stars": 4, "text": "Nice paper"}
GET /products/2/reviews  →  200  [{"stars": 4, "text": "Nice paper"}]
POST /products/1/reviews  {"stars": 3, "text": "The handle gets hot"}  →  201  {"stars": 3, "text": "The handle gets hot"}
GET /products/1/reviews  →  200  [{"stars": 5, …}, {"stars": 4, …}, {"stars": 3, "text": "The handle gets hot"}]
POST /products/99/reviews  {"stars": 5, "text": "Love it"}  →  404  {"error": "Product not found"}
GET /products/1  →  200  {"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}

Your task: add a GET and a POST route for /products/<int:product_id>/reviews. GET answers the product's list of reviews, or []; POST adds the review at the end of that list and answers 201 with it; both answer 404 when the product doesn't exist.


Assignment
Follow the Coding Tutorial to build get_reviews and add_review on the nested path.


Hint
Find the product first, with the loop and if of get_product. reviews.get(product_id, []) never fails on a missing key, and + [review] makes a new list with the review at the end: store it back under reviews[product_id].


STEP 1 OF 8
    Ctrl + Enter to check