DEV Community

Fiyinfoluwa Ojo
Fiyinfoluwa Ojo

Posted on

DELETE /items/:id: Removing Data from Your API with FastAPI

The D in CRUD

Today we complete another piece of CRUD : DELETE.
Removing data cleanly and safely is just as important
as creating it.

The DELETE Endpoint

@app.delete("/items/{item_id}", status_code=204)
def delete_item(item_id: int):
    db = SessionLocal()
    item = db.query(Item).filter(Item.id == item_id).first()
    if not item:
        db.close()
        raise HTTPException(status_code=404, detail="Item not found")
    db.delete(item)
    db.commit()
    db.close()
    return Response(status_code=204)
Enter fullscreen mode Exit fullscreen mode

Why 204 No Content?

204 means the request succeeded but there's nothing
to return. Sending a body after a DELETE is considered
bad practice : the resource is gone, there's nothing to say.

The Verification Step

The real proof of a working DELETE isn't the 204,
it's what happens when you try to GET the deleted item.

A proper DELETE implementation returns:

  • 204 on successful deletion
  • 404 when trying to access the deleted item
  • 404 when trying to delete a non-existent item

Postman Tests

Step 1 - All items before deletion

items fetched

Step 2 - Delete item 1

delete items

Step 3 - Try to GET item 1 again

items not found

Lessons Learned

DELETE is simple but the details matter :
204 not 200, no response body, and always
verify with a follow-up GET. That's how you
know your deletion actually worked.

Day 11 done. 19 more to go. 🔥

GDGoCBowen30dayChallenge

Top comments (0)