0
0
FlaskDebug / FixBeginner · 4 min read

How to Handle DELETE Request in Flask: Simple Guide

In Flask, handle a DELETE request by defining a route with methods=['DELETE'] and writing a function to process the deletion logic. Use request.method == 'DELETE' or Flask route decorators to respond to delete requests properly.
🔍

Why This Happens

Developers often forget to specify the DELETE method in the route's methods list, so Flask treats the request as a GET or POST and returns a 405 Method Not Allowed error.

python
from flask import Flask
app = Flask(__name__)

@app.route('/item/<int:id>')
def delete_item(id):
    # Intended to handle delete but missing methods=['DELETE']
    return f"Deleted item {id}", 200

if __name__ == '__main__':
    app.run()
Output
Method Not Allowed (405) error when sending DELETE request
🔧

The Fix

Add methods=['DELETE'] to the route decorator so Flask knows to accept DELETE requests. Then implement the logic to delete the item inside the function.

python
from flask import Flask, request
app = Flask(__name__)

@app.route('/item/<int:id>', methods=['DELETE'])
def delete_item(id):
    # Here you would add code to delete the item from your database
    return f"Deleted item {id}", 200

if __name__ == '__main__':
    app.run()
Output
When sending a DELETE request to /item/5, response: "Deleted item 5" with status 200
🛡️

Prevention

Always specify the HTTP methods your route should handle using the methods parameter in the @app.route decorator. Use tools like Postman or curl to test your endpoints with different HTTP methods. Follow RESTful API design principles to keep your routes clear and consistent.

⚠️

Related Errors

405 Method Not Allowed: Happens when the route does not accept the HTTP method used. Fix by adding the method to methods.

404 Not Found: Occurs if the URL pattern does not match. Check route URL parameters carefully.

Key Takeaways

Always include 'DELETE' in the route's methods list to handle delete requests.
Use Flask's route decorators to clearly specify which HTTP methods are accepted.
Test your API endpoints with tools like curl or Postman to verify behavior.
Follow RESTful conventions for clean and predictable API design.