How to Use methods Parameter in Route in Flask
In Flask, use the
methods parameter in the @app.route() decorator to specify which HTTP methods a route accepts, like GET or POST. For example, @app.route('/', methods=['GET', 'POST']) allows the route to handle both GET and POST requests.Syntax
The methods parameter is a list of HTTP methods that a Flask route will accept. It is passed as an argument to the @app.route() decorator.
- @app.route(path, methods=[...]): Defines the URL path and allowed HTTP methods.
- methods: A list of strings like
'GET','POST','PUT','DELETE', etc.
python
@app.route('/path', methods=['GET', 'POST']) def function_name(): pass
Example
This example shows a Flask app with a route that accepts both GET and POST requests. It returns different messages depending on the request method.
python
from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def home(): if request.method == 'POST': return 'This is a POST request' else: return 'This is a GET request' if __name__ == '__main__': app.run(debug=True)
Output
When accessed via browser (GET): This is a GET request
When accessed via POST (e.g., curl or form): This is a POST request
Common Pitfalls
Common mistakes when using the methods parameter include:
- Not specifying
methodsdefaults the route to only acceptGETrequests. - Using a string instead of a list for
methodscauses errors (e.g.,methods='POST'instead ofmethods=['POST']). - Forgetting to handle different methods inside the view function can cause unexpected behavior.
python
from flask import Flask, request app = Flask(__name__) # Wrong: methods as string @app.route('/wrong', methods='POST') def wrong(): return 'This will cause an error' # Right: methods as list @app.route('/right', methods=['POST']) def right(): return 'This works fine'
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| methods | List of HTTP methods the route accepts | methods=['GET', 'POST'] |
| GET | Retrieve data, default method if methods not set | methods=['GET'] |
| POST | Send data to server | methods=['POST'] |
| PUT | Update data | methods=['PUT'] |
| DELETE | Delete data | methods=['DELETE'] |
Key Takeaways
Use the methods parameter as a list to specify allowed HTTP methods in @app.route().
If methods is not set, the route only accepts GET requests by default.
Always handle different request methods inside your view function using request.method.
Pass methods=['POST'] not methods='POST' to avoid errors.
Common HTTP methods include GET, POST, PUT, and DELETE.