Handling HTTP Methods (GET, POST, PUT, DELETE)
Handling HTTP Methods (GET, POST, PUT, DELETE)
HTTP defines a set of request methods (also known as verbs) indicating the desired action to be performed on a given resource. By default, @app.route() only responds to GET requests. To build interactive web forms or REST APIs, routes must explicitly accept methods.
1. The methods Argument in @app.route
To allow multiple HTTP verbs on a route, supply a list to the methods parameter:
If a client sends an unsupported method (e.g., DELETE to /api/v1/articles), Flask automatically responds with an HTTP 405 Method Not Allowed header containing the allowed verbs.
2. Separate Route Handlers vs Consolidated Handlers
In RESTful design, you can either handle all methods in one view function using if request.method == '...', or separate them using modern route decorators:
3. Method Semantics Overview
| Method | Idempotent | Safe | Primary Purpose | Common Response Code |
|---|---|---|---|---|
| GET | Yes | Yes | Retrieve representation of a resource without side effects | 200 OK |
| POST | No | No | Submit data to create a new subordinate resource | 201 Created |
| PUT | Yes | No | Replace the entire target resource with payload | 200 OK / 204 No Content |
| PATCH | No | No | Apply partial modifications to a resource | 200 OK |
| DELETE | Yes | No | Remove the target resource permanently | 204 No Content |
| HEAD | Yes | Yes | Same as GET, but transfers status line and header section only | 200 OK |
| OPTIONS | Yes | Yes | Describe communication options for target resource (CORS preflight) | 204 No Content |
4. Automatic HEAD and OPTIONS Handling
Flask handles HEAD and OPTIONS automatically:
- Whenever you define a
GETroute, Flask automatically addsHEADsupport. If aHEADrequest arrives, Flask invokes the route handler, computes headers, but strips the response body before sending. - Flask automatically generates an
OPTIONSresponse listing allowed verbs in theAllowHTTP header.
Practice Quiz
@app.route('/test') is defined without the methods argument?DELETE request to a route configured with methods=['GET', 'POST']?The Flask Request Object & Data Parsing
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Dynamic URLs & Type Converters | The Flask Request Object & Data Parsing |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.