Start learning free

LESSON 20 OF 188 · BACKEND: YOUR FIRST API

Add a Product

Practice

Until now every route used GET, the method for reading. To send new data, a client uses POST. Flask picks the function by the path and the method together, so GET /products and POST /products can go to two different functions.

A POST carries a request body, usually a JSON object. request.get_json() reads it and gives you a Python dictionary. When something new is stored, the answer has the status 201 Created, written like the 404: the body, a comma, then the status. Here is the idea on another route:

messages = []

@app.post("/messages")
def add_message():
    data = request.get_json()
    messages.append(data["text"])
    return jsonify({"count": len(messages)}), 201

The client doesn't choose the id: the shop gives the new product the largest id so far, plus 1, and stores it in products, so every route sees it. Your code must give, in this order:

POST /products  {"name": "Plant", "price": 15, "category": "home"}  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}
POST /products  {"name": "Stapler", "price": 9, "category": "office"}  →  201  {"id": 6, "name": "Stapler", "price": 9, "category": "office"}
GET /products/6  →  200  {"id": 6, "name": "Stapler", …}
GET /products?category=office  →  200  [{"id": 2, …}, {"id": 4, …}, {"id": 6, …}]
GET /products/count  →  200  {"count": 6}

Your task: add a POST /products route, add_product, that reads the JSON body, gives the new product the next id, appends it to products and answers it with the status 201.


Assignment
Follow the Coding Tutorial to build add_product, from the route to the 201 answer.


Hint
Find the largest id with a variable that starts at 0 and a loop that keeps the biggest id it has seen. Build the new product in new_product, not product, and return it with , 201.


STEP 1 OF 10
    Ctrl + Enter to check