How to Get Request Method in Flask: Simple Guide
In Flask, you can get the HTTP request method by accessing
request.method inside a route function. This returns a string like GET or POST depending on the request type.Syntax
Use request.method inside a Flask route to get the HTTP method of the current request.
request: The Flask object representing the incoming HTTP request.method: A property that returns the HTTP method as a string (e.g.,GET,POST).
python
from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): method = request.method return f"Request method is: {method}"
Example
This example shows a Flask app that returns the HTTP method used to access the root URL. It supports both GET and POST methods.
python
from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return f"Request method is: {request.method}" if __name__ == '__main__': app.run(debug=True)
Output
When you visit http://localhost:5000/ in a browser, it shows: Request method is: GET
When you send a POST request (e.g., via curl or Postman), it shows: Request method is: POST
Common Pitfalls
Some common mistakes when getting the request method in Flask include:
- Not importing
requestfromflask. - Trying to access
request.methodoutside a route or request context, which causes errors. - Not specifying allowed methods in the route decorator, so POST requests may return 405 Method Not Allowed.
python
from flask import Flask app = Flask(__name__) @app.route('/') def index(): # Wrong: request not imported, will cause NameError return f"Method is: {request.method}" # Correct way: from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return f"Method is: {request.method}"
Quick Reference
Summary tips for getting request method in Flask:
- Always import
requestfromflask. - Access
request.methodinside route functions only. - Specify allowed HTTP methods in
@app.routedecorator. request.methodreturns a string likeGET,POST,PUT, etc.
Key Takeaways
Use request.method inside a Flask route to get the HTTP method as a string.
Always import request from flask before using it.
Specify allowed methods in the route decorator to handle POST or other methods.
Accessing request.method outside a request context causes errors.
request.method returns values like GET, POST, PUT, DELETE depending on the request.