DEV Community

kumar ramanathan
kumar ramanathan

Posted on

Rest api 3: Create Item in store

Requirement:
We have list stores , need to append item from the rest api end point using path param input as store name and item in request body.

our new method will be below for this case:

@app.post("/stores/<string:store_name>/items")
def create_item_in_store(store_name):
    request_data = request.get_json()
    for store in stores:
        if store["name"] == store_name:
            new_item = {"name": request_data["name"], "price": request_data["price"]}
            store["items"].append(new_item)
            return new_item, 201
    return {"message": "store not found"}, 404
Enter fullscreen mode Exit fullscreen mode

in post man using the below url and input hit the api end point :

now again retrieve all the data:

Now we will try to add more then one item in to the request, to access more than one item we need to modify our code logic little bit

@app.post("/stores/<string:store_name>/items")
def create_items_in_store(store_name):
    request_data = request.get_json()
    for store in stores:
        if store["name"] == store_name:
            for item in request_data["items"]:
                new_item = {"name": item["name"], "price": item["price"]}
                store["items"].append(new_item)
            return {"message": "items created"}, 201
    return {"message": "store not found"}, 404
Enter fullscreen mode Exit fullscreen mode

now hit the get stores again

Top comments (0)