Start learning free

LESSON 34 OF 188 · BACKEND: YOUR FIRST API

Project: The Shop So Far

Practice

This project puts most of what you have built so far into one new route. A product page shows the product's rating: the average of the stars in its reviews. The rating belongs to one product, so it gets a nested path under that product, just like the reviews: /products/1/rating.

An average in Python: collect the numbers in a list, then divide sum by len. round(..., 2) keeps 2 decimal places, the way get_stats does for the prices.

temperatures = [20, 23, 22]
average = round(sum(temperatures) / len(temperatures), 2)
print(average)   # 21.67

No numbers, no average: when the list is empty, len is 0. Dividing by 0 crashes with ZeroDivisionError, and Flask would answer 500. So check for an empty list first and answer None, which is null in JSON. A product with no reviews still exists, so it gets 200 with a null rating. A product that isn't in products gets 404, as always.

The test requests, in this order, and what your code must answer:

GET /products/1/rating    →  200  {"product_id": 1, "rating": 4.5}
GET /products/3/rating    →  200  {"product_id": 3, "rating": 2.0}
GET /products/2/rating    →  200  {"product_id": 2, "rating": null}
GET /products/99/rating   →  404  {"error": "Product not found"}
POST /products/1/reviews  {"stars": 5, "text": "My favourite mug"}  →  201  (the review)
GET /products/1/rating    →  200  {"product_id": 1, "rating": 4.67}
POST /products/2/reviews  {"stars": 3, "text": "Thin pages"}  →  201  (the review)
GET /products/2/rating    →  200  {"product_id": 2, "rating": 3.0}
DELETE /products/3        →  204  (empty)
GET /products/3/rating    →  404  {"error": "Product not found"}

Your task: at the end of the file, add a route for GET /products/<int:product_id>/rating with the function get_rating. It answers the "product_id" and a "rating": the average of the product's stars rounded to 2 places, or null when the product has no reviews. When no product has that id, it answers 404 with "Product not found".


Assignment
Follow the Coding Tutorial to add the /rating route at the end of the file: find the product, collect the stars of its reviews, and answer their rounded average, or a null rating when there are none.


Hint
Copy the shape of get_reviews to find the product and to answer the 404 with error_response, and the shape of get_stats for the list, the empty check and the rounded average. Check for an empty list before you divide.


STEP 1 OF 12
    Ctrl + Enter to check