HTTP methods tell a web server what action you want to do with data. They help your app get, send, update, or delete information.
HTTP methods (GET, POST, PUT, DELETE) in Flask
from flask import Flask, request app = Flask(__name__) @app.route('/resource', methods=['GET', 'POST', 'PUT', 'DELETE']) def resource(): if request.method == 'GET': return 'Get data' elif request.method == 'POST': return 'Create data' elif request.method == 'PUT': return 'Update data' elif request.method == 'DELETE': return 'Delete data'
Use @app.route with methods to specify allowed HTTP methods.
Check request.method to handle each method differently.
@app.route('/items', methods=['GET']) def get_items(): return 'List of items'
@app.route('/items', methods=['POST']) def add_item(): data = request.json return f"Added item: {data['name']}"
@app.route('/items/<int:id>', methods=['PUT']) def update_item(id): data = request.json return f"Updated item {id} with name {data['name']}"
@app.route('/items/<int:id>', methods=['DELETE']) def delete_item(id): return f"Deleted item {id}"
This Flask app manages a simple list of items using all four HTTP methods. You can get all items, add a new item, update an existing item, or delete an item by its ID.
from flask import Flask, request app = Flask(__name__) items = {1: 'apple', 2: 'banana'} @app.route('/items', methods=['GET']) def get_items(): return items @app.route('/items', methods=['POST']) def add_item(): new_id = max(items.keys()) + 1 if items else 1 data = request.json items[new_id] = data['name'] return {'id': new_id, 'name': items[new_id]}, 201 @app.route('/items/<int:id>', methods=['PUT']) def update_item(id): if id in items: data = request.json items[id] = data['name'] return {'id': id, 'name': items[id]} else: return {'error': 'Item not found'}, 404 @app.route('/items/<int:id>', methods=['DELETE']) def delete_item(id): if id in items: del items[id] return {'message': f'Item {id} deleted'} else: return {'error': 'Item not found'}, 404
GET requests should not change data; they only fetch it.
POST is for creating new data, PUT is for updating existing data.
DELETE removes data and should be used carefully.
HTTP methods tell the server what action to do with data.
Use GET to read, POST to create, PUT to update, and DELETE to remove data.
Flask lets you handle these methods easily with routes and request checks.
Practice
Solution
Step 1: Understand HTTP methods purpose
GET is used to request data without modifying it, so it is safe and idempotent.Step 2: Match method to Flask usage
In Flask, GET routes are used to send data back to the client without changing server state.Final Answer:
GET -> Option CQuick Check:
Retrieve data = GET [OK]
- Confusing POST with GET for data retrieval
- Using DELETE to get data
- Thinking PUT is for reading data
Solution
Step 1: Recall Flask route syntax for methods
Flask uses the 'methods' keyword argument as a list of strings to specify allowed HTTP methods.Step 2: Check each option's syntax
@app.route('/submit', methods=['GET', 'POST']) correctly uses methods=['GET', 'POST']. Others have wrong keywords or wrong data types.Final Answer:
@app.route('/submit', methods=['GET', 'POST']) -> Option BQuick Check:
Correct keyword and list format = @app.route('/submit', methods=['GET', 'POST']) [OK]
- Using 'method' instead of 'methods'
- Passing methods as a string instead of list
- Using unknown keywords like 'allow_methods'
@app.route('/item/', methods=['DELETE'])
def delete_item(id):
return f"Deleted item {id}", 200Solution
Step 1: Analyze route and method
The route accepts DELETE requests with an integer id parameter and returns a string with status 200.Step 2: Understand response for DELETE request
Since the method matches and function returns a message with 200, the client receives that message and status.Final Answer:
"Deleted item <id>" with status 200 -> Option AQuick Check:
DELETE request handled correctly = "Deleted item <id>" with status 200 [OK]
- Expecting 404 if route exists
- Confusing DELETE with GET behavior
- Assuming empty response without checking code
@app.route('/update', methods=['PUT'])
def update():
data = request.get_json()
return 'Updated', 200Solution
Step 1: Check usage of 'request'
The function uses 'request.get_json()' but 'request' is not imported from Flask, causing a NameError.Step 2: Verify other parts
Method 'PUT' is valid, route syntax is correct, and returning string with status 200 is allowed.Final Answer:
Missing import of 'request' from Flask -> Option AQuick Check:
Using 'request' without import causes error [OK]
- Forgetting to import 'request'
- Thinking PUT is invalid method
- Assuming string return is wrong
Solution
Step 1: Understand RESTful design
PUT and DELETE are standard methods for update and delete at the same resource URL.Step 2: Implement in Flask
Flask allows one route to handle multiple methods; inside the function, you check request.method to run correct code.Final Answer:
Use one route with methods=['PUT', 'DELETE'] and check request.method inside the function -> Option DQuick Check:
Multiple methods on one route with method check = Use one route with methods=['PUT', 'DELETE'] and check request.method inside the function [OK]
- Creating separate URLs for same resource actions
- Using POST or GET incorrectly for update/delete
- Not checking request.method inside route
Ready to prove it?
Pass the test and this pattern moves unknown
