Introduction to Flask and the delete() Method
Flask is one of the most popular web development frameworks in Python. Using Flask, you can build lightweight and speedy web applications and easily manage them. One of the attractive features of Flask is that it allows you to perform CRUD operations (Create, Read, Update, Delete) on data easily.
In this article, we will discuss the delete() method in Flask. The delete() method is typically used to delete a specific resource from an API or data endpoint. This method allows us to remove the specified resource from the server by sending a delete request.
You can use the delete method in Flask, along with its combination with routes and URLs, to specify endpoints for deleting specific resources. This subject is very important, especially when you need to manage data created by users.
Let's take a look at the code section to better understand how we can utilize this method.
How to Use Flask.delete()
from flask import Flask, jsonify, request
app = Flask(__name__)
# Assume that this is our list of data
items = [{"id": 1, "name": "item1"}, {"id": 2, "name": "item2"}]
@app.route('/items/', methods=['DELETE'])
def delete_item(item_id):
global items
items = [item for item in items if item['id'] != item_id]
return jsonify({'message': 'Item deleted successfully'}), 200
if __name__ == '__main__':
app.run(debug=True)
Code Explanation
Line 1
from flask import Flask, jsonify, request
This line imports the Flask library and the necessary modules needed for it.
Line 2
app = Flask(__name__)
Creates a Flask instance called
app
that can be used to define routes and methods.Line 3
items = [{"id": 1, "name": "item1"}, {"id": 2, "name": "item2"}]
We have a list of items that will store our data. Here we have two instances.
Line 4
@app.route('/items/', methods=['DELETE'])
Defines the route
/items/<int:item_id>
for the DELETE method. item_id
is the identifier of the resource we want to delete.Line 5
def delete_item(item_id):
Defines a function that performs the delete operation.
Line 6
global items
Declares the global variable
items
to access the external list from within the function.Line 7
items = [item for item in items if item['id'] != item_id]
Filters the
items
list to remove the item whose id
matches the specified item_id
.Line 8
return jsonify({'message': 'Item deleted successfully'}), 200
Returns a JSON response with a success message and status code 200 indicating successful deletion.
Line 9
if __name__ == '__main__':
Checks if this file is being run directly or imported.
Line 10
app.run(debug=True)
Runs the Flask application in debug mode, which helps us to better see errors.