Description
The create_item() function generates new item IDs using len(_get_items()) + 1. This approach causes duplicate IDs when items are deleted from the middle or beginning of the list.
Steps to Reproduce
- Create item A →
id=1
- Create item B →
id=2
- Delete item A (id=1) — list now contains only item B (id=2), length = 1
- Create item C →
len([B]) + 1 = 2 → id=2 (duplicate!)
Now two items (B and C) both have id=2.
Expected Behavior
Each item should have a globally unique ID that is never reused, regardless of deletions.
Actual Behavior
IDs can collide after deletions because the ID generation is based on the current list length rather than a monotonically increasing counter.
Impact
PATCH /items/:id and DELETE /items/:id will only operate on the first item found with the duplicate ID (via next()), making the second item inaccessible.
- Clients caching items by ID will get stale/incorrect data.
Suggested Fix
Replace the length-based ID with an auto-incrementing counter:
_next_id = 1
def _new_id():
global _next_id
current = _next_id
_next_id += 1
return current
And update create_item():
item = {
"id": _new_id(),
"name": data["name"],
"done": False,
}
Also update reset_items() to reset the counter for tests:
def reset_items():
global _next_id
_items_store.clear()
_next_id = 1
Affected File
app.py — create_item() function (line ~29)
Description
The
create_item()function generates new item IDs usinglen(_get_items()) + 1. This approach causes duplicate IDs when items are deleted from the middle or beginning of the list.Steps to Reproduce
id=1id=2len([B]) + 1 = 2→ id=2 (duplicate!)Now two items (B and C) both have
id=2.Expected Behavior
Each item should have a globally unique ID that is never reused, regardless of deletions.
Actual Behavior
IDs can collide after deletions because the ID generation is based on the current list length rather than a monotonically increasing counter.
Impact
PATCH /items/:idandDELETE /items/:idwill only operate on the first item found with the duplicate ID (vianext()), making the second item inaccessible.Suggested Fix
Replace the length-based ID with an auto-incrementing counter:
And update
create_item():Also update
reset_items()to reset the counter for tests:Affected File
app.py—create_item()function (line ~29)