Flask HTTP Methods
HTTP (Hypertext Transfer Protocol) is the foundation of communication on the World Wide Web. Every web framework, including Flask, uses HTTP methods to handle requests and transfer data between the client (browser) and the server.
The methods are given in the following table.
methods
parameter inside the @app.route() decorator.POST Method
To demonstrate the POST method, let’s first create a simple login form (login.html) that collects a username and password from the user.
Example
login.html
<html>
<body>
<form action="http://localhost:5000/login" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="yourname"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>
post_example.py
from flask import Flask, request
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
yourname = request.form['yourname']
password1 = request.form['pass']
if yourname == "hema" and password1 == "gocourse":
return f"Welcome {yourname}"
else:
return "Invalid credentials"
if __name__ == '__main__':
app.run(debug=True)
Output
- Run the Flask server : python post_example.py
- Open login.html in the browser.
- Enter Name: hema and Password: gocourse, then click Submit.
- The browser will display
Welcome hema
Here, the form data is sent to the server using the POST method, and it does not appear in the browser’s
URL.
GET Method
Now, let’s implement the same login form using the GET method.
Example
login.html
<html>
<body>
<form action="http://localhost:5000/login" method="get">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="yourname"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>
get_example.py
from flask import Flask, request
app = Flask(__name__)
@app.route('/login', methods=['GET'])
def login():
yourname = request.args.get('yourname')
password1 = request.args.get('pass')
if yourname == "hema" and password1 == "gocourse":
return f"Welcome {yourname}"
else:
return "Invalid credentials"
if __name__ == '__main__':
app.run(debug=True)
Output
- Run the Flask server : python get_example.py
- Open login.html in the browser.
- Enter Name: hema and Password: gocourse, then click Submit.
- The browser will display
Welcome hema
However, in this case the data is sent as part of the URL, for example:
http://localhost:5000/login?yourname=hema&pass=gocourse
This is the key difference between GET and POST methods.
Key Differences: GET vs POST
- GET → Data is visible in the URL, useful for simple queries, but not secure for sensitive data.
- POST → Data is hidden in the request body, making it more secure for sending form submissions like passwords.