Skip to content

Flask - HTTP Methods

The HyperText Transfer Protocol (HTTP) is the foundation of data communication on the World Wide Web. It defines a set of request methods (often called “HTTP verbs”) to indicate the desired action to be performed for a given resource (identified by a URL).

Common HTTP Methods:

Sr.NoMethodDescription
1GETRequests retrieval of information identified by the Request-URI. Should only retrieve data and have no other effect. This is the most common method used when browsing.
2POSTSubmits data to be processed to the identified resource (e.g., submitting a web form, uploading a file). Often results in a change in state or side effects on the server.
3PUTReplaces all current representations of the target resource with the request payload. Often used for updating an existing resource entirely.
4DELETERequests that the origin server delete the resource identified by the Request-URI.
5HEADIdentical to GET except that the server MUST NOT return a message-body in the response. Useful for retrieving meta-information about the resource without transferring the entire content.
6OPTIONSRequests information about the communication options available for the target resource (e.g., which HTTP methods are supported).
7PATCHApplies partial modifications to a resource. Unlike PUT, it only updates the specified fields.

By default, Flask routes only respond to GET requests (and implicitly HEAD and OPTIONS). To allow a route to handle other methods, you must explicitly list them using the methods argument in the @app.route() decorator.

Example: Handling GET and POST for a Login Form

Section titled “Example: Handling GET and POST for a Login Form”

This example demonstrates a single URL (/login) that displays a form when accessed via GET and processes the submitted form data when accessed via POST.

  1. Create an HTML template named login_page.html in your templates folder:
<!DOCTYPE html>
<html>
<head>
<title>Login Example</title>
</head>
<body>
<h1>Login Form</h1>
<form action="{{ url_for('handle_login') }}" method="post">
<p>Enter Name: <input type="text" name="username"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>

Note the method="post" in the <form> tag.

  1. Create the Flask application script (app.py):
from flask import Flask, redirect, url_for, request, render_template
app = Flask(__name__)
# Route for successful login
@app.route('/success/<name>')
def login_success(name):
return f'Welcome {name}!'
# Route to handle both displaying the form (GET) and processing it (POST)
@app.route('/login', methods=['POST', 'GET'])
def handle_login():
if request.method == 'POST':
# Request is POST: access form data submitted
user_name = request.form['username'] # Access data using the input's 'name' attribute
# Redirect to the success page, passing the username
return redirect(url_for('login_success', name=user_name))
else:
# Request is GET: display the login form template
return render_template('login_page.html')
if __name__ == '__main__':
app.run(debug=True)

Explanation:

  • methods=['POST', 'GET']: This explicitly allows the /login route to handle both POST and GET requests.
  • request.method: Inside the handle_login function, we check the current request’s method.
  • If request.method == 'POST': This block executes when the form is submitted. We retrieve the value of the input field named username from request.form (which holds form data submitted in the request body). Then, we redirect the user to the login_success route, building the URL with url_for and passing the extracted user_name.
  • If request.method == 'GET' (the else block): This executes when the user first navigates to /login. We render the login_page.html template to display the form.
  • request.args: If data were sent via the URL query string (e.g., /search?term=flask), you would access it using request.args.get('term'). This is typical for GET requests.

Running the Example:

  1. Save the files and run python app.py.

  2. Open your browser and go to http://127.0.0.1:5000/login. You’ll see the login form (handled by the GET request).

  3. Enter a name (e.g., “Alice”) and click Submit.

Description of interaction:

The browser sends a POST request to /login with the name you entered in the form data. Flask routes this to handle_login(). The if request.method == 'POST' block executes, retrieves “Alice” from request.form['username'], and generates a redirect response to /success/Alice. The browser receives this redirect and makes a new GET request to /success/Alice. Flask routes this to login_success(name='Alice'), which returns the “Welcome Alice!” message.