Search code examples
pythonrestdictionaryputbottle

Update a dictionary of item in Python using bottle framework


I am doing crud rest API in Python with bottle framework and I am having trouble updating an item by id in a dictionary. So far I have done create, read, and delete.

Here is my dictionary:

items = [
    {"id": "1", "name": "a", "lastname": "a"},
    {"id": "2", "name": "b", "lastname": "b"},
    {"id": "3", "name": "c", "lastname": "c"}, 
]

And here is my route:

from bottle import get, post, run, redirect, request, response, view, put

@put("/items/<item_id>")
def updated_item(item_id):
    for item in items:
        if item["id"] == item_id:
        new_name = request.forms.get("name")
        new_lastname = request.forms.get("lastname")
            
        #(I need some help here)
    
    return redirect("/items")

Solution

  • You don't need to iterate on items, if items index is constant. That means that there is mapping between the index in the list and the item["id"]:

    @put("/items/<item_id>")
    def updated_item(item_id):
        
        new_name = request.forms.get("name")
        new_lastname = request.forms.get("lastname")
            
        items[int(item_id) - 1] = {"id": item_id, "name": new_name, "lastname": "new_lastname"}
    
    return redirect("/items")
    

    If you delete items, just keep an empty element to keep the order:

    @delete("/items/<item_id>"):
    def delete_item(item_id):
        
        items[int(item_id)] = {}
    

    Of course, if id is arbitrary, this won't work, e.g.:

    items = [
    {"id": "12", "name": "a", "lastname": "a"},
    {"id": "21", "name": "b", "lastname": "b"},
    {"id": "53", "name": "c", "lastname": "c"},  
    ]
    

    If this is the case, you should consider using an in memory database (e.g. SQLite) which is great at housekeeping of records like you just showed. The database will then replace items (well, it's going to be a table).