Bird
Raised Fist0
Flaskframework~10 mins

HTTP methods (GET, POST, PUT, DELETE) in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - HTTP methods (GET, POST, PUT, DELETE)
Client sends HTTP request
↓
Server receives request
↓
Check HTTP method
↓
Read
↓
Send response back to client
The server receives a request, checks the HTTP method (GET, POST, PUT, DELETE), performs the related action, then sends a response.
Execution Sample
Flask
from flask import Flask, request
app = Flask(__name__)

@app.route('/item', methods=['GET', 'POST', 'PUT', 'DELETE'])
def item():
    if request.method == 'GET':
        return 'Read item'
    elif request.method == 'POST':
        return 'Create item'
    elif request.method == 'PUT':
        return 'Update item'
    elif request.method == 'DELETE':
        return 'Delete item'

if __name__ == '__main__':
    app.run(debug=True)
A Flask route that handles GET, POST, PUT, DELETE methods and returns a message for each. Note: Flask automatically returns 405 for unsupported methods like PATCH.
Execution Table
StepHTTP MethodCondition CheckedAction TakenResponse Sent
1GETrequest.method == 'GET'Return 'Read item''Read item'
2POSTrequest.method == 'POST'Return 'Create item''Create item'
3PUTrequest.method == 'PUT'Return 'Update item''Update item'
4DELETErequest.method == 'DELETE'Return 'Delete item''Delete item'
5PATCHRoute method check fails (before function)405 Method Not Allowed (Flask default)405 Method Not Allowed
💡 Execution stops after matching HTTP method condition. Unsupported methods like PATCH trigger Flask's 405 before entering the function.
Variable Tracker
VariableStartAfter GETAfter POSTAfter PUTAfter DELETEPATCH (not entered)
request.methodNone'GET''POST''PUT''DELETE''PATCH' (function not called)
Key Moments - 3 Insights
Why does the server return 'Read item' only when the method is GET?
Because in the execution_table row 1, the condition 'request.method == 'GET'' is true only for GET requests, triggering the 'Read item' response.
What happens if the client sends a PATCH request?
As shown in execution_table row 5, PATCH is not in the route's methods list, so Flask returns 405 Method Not Allowed before entering the function.
Why do we check the HTTP method inside the route function?
Because the same URL can handle different actions depending on the method (RESTful design), as shown in the execution_table where each method triggers a different response.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what response is sent when the HTTP method is PUT?
A'Create item'
B'Update item'
C'Delete item'
D'Read item'
💡 Hint
Check the row where HTTP Method is PUT in the execution_table.
At which step does the server return 'Delete item'?
AStep 4
BStep 2
CStep 3
DStep 1
💡 Hint
Look for the row with HTTP Method DELETE in the execution_table.
If the client sends a PATCH request, what will the server respond with?
A'Update item'
B'Delete item'
C405 Method Not Allowed
D'Create item'
💡 Hint
See the last row in the execution_table for unsupported methods.
Concept Snapshot
HTTP methods define RESTful actions on a resource:
GET = read/retrieve data
POST = create new data
PUT = update/replace existing data
DELETE = remove/delete data
In Flask, specify methods in @app.route() and check request.method inside for logic. Unsupported methods auto-return 405.
Full Transcript
This example shows how a Flask server handles different HTTP methods (GET, POST, PUT, DELETE) on the same '/item' URL following REST principles. The route specifies allowed methods. Inside the function, if-elif checks request.method to return appropriate messages: 'Read item' for GET, etc. For unsupported methods like PATCH, Flask returns 405 Method Not Allowed without calling the function.

Practice

(1/5)
1. Which HTTP method is typically used in Flask to retrieve data without changing anything on the server?
easy
A. PUT
B. POST
C. GET
D. DELETE

Solution

  1. Step 1: Understand HTTP methods purpose

    GET is used to request data without modifying it, so it is safe and idempotent.
  2. Step 2: Match method to Flask usage

    In Flask, GET routes are used to send data back to the client without changing server state.
  3. Final Answer:

    GET -> Option C
  4. Quick Check:

    Retrieve data = GET [OK]
Hint: GET reads data, POST creates, PUT updates, DELETE removes [OK]
Common Mistakes:
  • Confusing POST with GET for data retrieval
  • Using DELETE to get data
  • Thinking PUT is for reading data
2. Which of the following Flask route definitions correctly allows handling both GET and POST methods?
easy
A. @app.route('/submit', allow_methods=['GET', 'POST'])
B. @app.route('/submit', methods=['GET', 'POST'])
C. @app.route('/submit', methods='GET, POST')
D. @app.route('/submit', method=['GET', 'POST'])

Solution

  1. Step 1: Recall Flask route syntax for methods

    Flask uses the 'methods' keyword argument as a list of strings to specify allowed HTTP methods.
  2. 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.
  3. Final Answer:

    @app.route('/submit', methods=['GET', 'POST']) -> Option B
  4. Quick Check:

    Correct keyword and list format = @app.route('/submit', methods=['GET', 'POST']) [OK]
Hint: Use methods=['GET', 'POST'] exactly in route decorator [OK]
Common Mistakes:
  • Using 'method' instead of 'methods'
  • Passing methods as a string instead of list
  • Using unknown keywords like 'allow_methods'
3. What will be the output when a client sends a DELETE request to this Flask route?
@app.route('/item/', methods=['DELETE'])
def delete_item(id):
    return f"Deleted item {id}", 200
medium
A. "Deleted item <id>" with status 200
B. 404 Not Found error
C. Method Not Allowed error
D. Empty response with status 204

Solution

  1. Step 1: Analyze route and method

    The route accepts DELETE requests with an integer id parameter and returns a string with status 200.
  2. 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.
  3. Final Answer:

    "Deleted item <id>" with status 200 -> Option A
  4. Quick Check:

    DELETE request handled correctly = "Deleted item <id>" with status 200 [OK]
Hint: Route method matches request method, so response is returned [OK]
Common Mistakes:
  • Expecting 404 if route exists
  • Confusing DELETE with GET behavior
  • Assuming empty response without checking code
4. Identify the error in this Flask route that should handle PUT requests:
@app.route('/update', methods=['PUT'])
def update():
    data = request.get_json()
    return 'Updated', 200
medium
A. Missing import of 'request' from Flask
B. Incorrect HTTP method name 'PUT'
C. Route decorator syntax is invalid
D. Function must return JSON, not string

Solution

  1. Step 1: Check usage of 'request'

    The function uses 'request.get_json()' but 'request' is not imported from Flask, causing a NameError.
  2. Step 2: Verify other parts

    Method 'PUT' is valid, route syntax is correct, and returning string with status 200 is allowed.
  3. Final Answer:

    Missing import of 'request' from Flask -> Option A
  4. Quick Check:

    Using 'request' without import causes error [OK]
Hint: Always import 'request' to access request data [OK]
Common Mistakes:
  • Forgetting to import 'request'
  • Thinking PUT is invalid method
  • Assuming string return is wrong
5. You want to create a Flask API endpoint to update a user's email using PUT and delete the user using DELETE at the same URL '/user/'. Which is the best way to define this in Flask?
hard
A. Use GET method for both update and delete actions
B. Create two separate routes with different URLs for PUT and DELETE
C. Use only POST method and check a hidden field for action
D. Use one route with methods=['PUT', 'DELETE'] and check request.method inside the function

Solution

  1. Step 1: Understand RESTful design

    PUT and DELETE are standard methods for update and delete at the same resource URL.
  2. Step 2: Implement in Flask

    Flask allows one route to handle multiple methods; inside the function, you check request.method to run correct code.
  3. Final Answer:

    Use one route with methods=['PUT', 'DELETE'] and check request.method inside the function -> Option D
  4. Quick Check:

    Multiple methods on one route with method check = Use one route with methods=['PUT', 'DELETE'] and check request.method inside the function [OK]
Hint: One route, multiple methods, check request.method inside [OK]
Common Mistakes:
  • Creating separate URLs for same resource actions
  • Using POST or GET incorrectly for update/delete
  • Not checking request.method inside route
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard