Part 6: Building a User-Friendly Todo App with Flask - Step-by-Step Guide to Delete Todo and Category Items via DELETE Requests
Hey everyone, welcome to the sixth part of my Flask-based basic todo application series. In this post, I'll guide you through how you can delete your todo and category items via DELETE requests in your Flask todo app. Let's dive in!.
For Todo Items:
to begin copy the code bellow and use it to replace the deleteTodo function
function deleteTodo(todoId) {
// Perform a DELETE request to the specified todo ID
fetch(`/todos/${todoId}`, {
method: "DELETE", // Using the DELETE method
})
.then(response => {
// Check if the response is successful (status code 200-299)
if (response.ok) {
console.log(`Todo with ID ${todoId} deleted`); // Log success message
window.location.replace("http://127.0.0.1:5000"); // Redirect to home page after deletion
// Optionally, you can remove the deleted todo from the UI here
} else {
console.error('Error deleting todo', response.statusText); // Log error if deletion fails
}
})
.catch(error => {
console.error('Error:', error); // Catch and log any errors during the API request
});
}
This JavaScript function is triggered whenever the user clicks on the delete (trash) icon and sends a DELETE request to delete a todo item with the specified ID. Upon success, it logs a success message, redirects to the home page, and optionally removes the deleted todo from the user interface. If there's an error during the deletion process, it logs an error message
Now in your app.py file lets create our delete todo endpoint by adding in the codes below
@app.route('/todos/<id>', methods=['DELETE'])
def delete_todo(id):
try:
# Fetch the todo with the specified ID from the database
todo = Todo.query.get(id)
if not todo:
return jsonify({'error': 'Todo not found'}), 404 # Return a 404 error if todo not found
# Delete the fetched todo from the database
db.session.delete(todo)
# Commit the changes to the database
db.session.commit()
# Flash a success message to indicate successful deletion
flash("Todo was deleted successfully")
# Return a success message with status code 204 (No Content)
return jsonify({'message': 'Success!'}), 204
except Exception as e:
db.session.close() # Close the session in case of an exception
# Optionally, abort with a 404 error code or handle the exception as needed
# abort(404)
This Python code defines a route that listens for DELETE requests to delete a todo item based on its ID. It fetches the todo item from the database using the provided ID, deletes it from the database, commits the changes, flashes a success message, and returns a success message with a status code of 204 if successful. If there's an exception during this process, it closes the session or optionally handles the exception by aborting with a 404 error code.
Refresh your page, click the delete icon of any todo item, and see it removed from the todo list.
Thats all for deleting todo items, refresh your page and click on the delete icon (trash icon) of any todo item and you will see that the item is removed from the todo list.
For Deleting Categories:
to begin copy the code bellow and use it to replace the deleteCategory function
function deleteCategory(categoryId) {
// Send a DELETE request to the specified category ID route
fetch(`/categories/${categoryId}`, {
method: "DELETE", // Using the DELETE HTTP method
})
.then(response => {
if (response.ok) {
// Log success message if the deletion is successful
console.log(`Category with ID ${categoryId} deleted`);
// Redirect to the home page after successful deletion
window.location.replace("http://127.0.0.1:5000");
// Optionally, remove the deleted category from the UI here
} else {
// Log an error if deletion fails
console.error('Error deleting category', response.statusText);
}
})
.catch(error => {
// Log any errors that occur during the request
console.error('Error:', error);
});
}
This JavaScript function performs a DELETE request to a specific category ID endpoint. If the response status is successful (status code 200-299), it logs a success message, redirects the user to the home page (http://127.0.0.1:5000), and optionally removes the deleted category from the user interface. If the deletion fails or encounters an error, it logs an error message.
Now in your app.py file lets create our delete todo endpoint by adding in the codes below
@app.route('/categories/<int:id>', methods=['DELETE'])
def delete_category(id):
try:
# Retrieve the category using the provided ID from the URL
category = Category.query.get(id)
# Check if the category exists
if category:
# Delete the category from the database
db.session.delete(category)
db.session.commit()
# Return a success message and status code 204 (no content)
return jsonify({'message': 'Category deleted successfully'}), 204
else:
# If category does not exist, return a 404 error
return jsonify({'error': 'Category not found'}), 404
except Exception as e:
# Rollback changes if any exception occurs
db.session.rollback()
# Return an error message and status code 500 (server error)
return jsonify({'error': str(e)}), 500
The above route handles HTTP DELETE requests to a specific category ID endpoint (/categories/<int:id>). It attempts to delete the category corresponding to the provided ID from the database. If the category exists, it gets deleted, and a success message with a status code 204 (no content) is returned. If the category does not exist, it returns a 404 error. If an exception occurs during the deletion process, it rolls back any changes made and returns a server error (status code 500) along with the error details.
Refresh your page, click the delete icon of any category item, and see it removed from the category list.
That wraps up this part of the series. Check out the video below for a step-by-step guide. Feel free to ask any questions or leave comments below. Thanks for reading, and until next time!
Todo Series Parts:
- Part 1: Building a User-Friendly Todo App with Flask - A Step-by-Step Guide for Setting up Flask Application template
- Part 2: Building a User-Friendly Todo App with Flask - A Step-by-Step Guide for setting up our models with foreign key relationships
- Part 3: Building a User-Friendly Todo App with Flask - A Step-by-Step Guide to Performing GET Operations and Rendering Data on HTML Pages
- Part 4: Building a User-Friendly Todo App with Flask - Step-by-Step Guide to Perform Form Submissions via POST Requests
- Part 5: Building a User-Friendly Todo App with Flask - Step-by-Step Guide to Update Todo and Category Items via PATCH Requests
- Part 6: Building a User-Friendly Todo App with Flask - Step-by-Step Guide to Delete Todo and Category Items via DELETE Requests