
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) 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 Step 2 - D
Continue reading on Dev.to Python
Opens in a new tab



