Wednesday, December 25, 2024
Google search engine
HomeLanguagesFlask HTTP methods, handle GET & POST requests

Flask HTTP methods, handle GET & POST requests

In this article, we are going to learn about how to handle GET and POST requests of the flask HTTP methods in Python.

HTTP Protocol is necessary for data communication. In the context of the World Wide Web, an HTTP method is a request method that a client (e.g. a web browser) can use when making a request to a server (e.g. a web server). There are several HTTP methods that a client can use when making a request. In Flask, there are different methods to handle HTTP requests. e.g GET, POST, PUT, DELETE, HEAD. These methods are used to Send, Request, and Modify data on the server. 

Commonly used HTTP methods

First will see the explanation of various commonly used HTTP methods. afterward, we gonna create a simple flask project that will demonstrate the handling of user login using HTTP POST and GET methods.

GET: This method is used to retrieve data from the server. e.g In an eCommerce application, there is a search button to search for an item. after entering a keyword if we noticed, the keyword you searched for gets displayed in the URL. This request is used when the data is not sensitive.

POST: This method makes enables users to send data over to the server. e.g In any authentication-enabled application, the registration and login form is the best example for the post method. Whenever we enter Information and submit the data get transferred over to the POST request. And if we noticed, unlike get request there is no information will be ever displayed in the URL.

PUT: This method is used to update an existing resource on the server. Developers always prefer POST over PUT.

DELETE: This method is used to delete a resource on the server.

HEAD: Retrieves the resources headers, Without the resource itself. This request is like a GET request but it does not return a response body.

CONNECT: Establishes a tunnel to the server identified by the target resource.

OPTIONS: Describes the communication options for the target resource.

TRACE: Performs a message loop-back test along the path to the target resource.

PATCH: Applies partial modifications to a resource.

How to handle GET & POST requests using flask in Python

To handle Requests in flask we are having a route decorator. In that, there is a methods attribute that indicates what type of request a particular function is accepting. If we keep its value empty then it by default accepts a GET request. Otherwise, we can mention methods as given in the below syntax

Syntax: @app.routes(‘/example’, methods=[‘GET’, ‘POST])

Code example to handle GET & POST requests

In this example, the user gets a login form through which they can submit their credentials. In the backend, we are getting that username. To get the value of a particular input we have to use their name attribute. We have to set up the flask app to implement this. 

Stepwise implementation:

Step 1: Create a new project folder in which we have one templates folder to store HTML files and outside of the templates folder our python file will be stored. So, we have created one “login.html” file and an “app.py” file.

 

Step 2: In this step, we have created a simple login form using HTML in which we have created two login forms to explain GET request and POST request separately. In first form we are using GET request to login and in the second one we are using POST request to login. Note that this HTML page is saved in templates folder as explained in first step.

HTML




<!-- templates/login.html-->
 
<html>
 
<head>
    <title>Handling of http get and post request</title>
    <style>
        div {
            width: 400px;
            border: 1px solid green;
            padding: 10px;
            margin-bottom: 5px;
        }
    </style>
</head>
 
<body>
 
    <div>
<!-- url_for will route the forms request to
appropriate function that user made to handle it.-->
<!--we will Retrieve submitted values of inputs
on the backend side using 'name' field of form.-->
        <h1>Handle GET Request</h1>
        <form method="GET"
              action="{{ url_for('handle_get') }}">
            <input type="text"
                   name="username"
                   placeholder="Username">
            <input type="password"
                   name="password"
                   placeholder="Password">
            <button type="submit">submit</button>
        </form>
    </div>
 
    <div>
        <h1>Handle POST Request</h1>
        <form method="POST"
              action="{{ url_for('handle_post') }}">
            <input type="text"
                   name="username"
                   placeholder="Username">
            <input type="password"
                   name="password"
                   placeholder="Password">
            <button type="submit">submit</button>
        </form>
    </div>
</body>
 
</html>


Output: This below output is a simple HTML form in which we have not applied any operation.

 

Step 3: In this step, we have created a app.py Python file In which we have created three functions handle_get(), handle_post(), and logout() to handle user login. To handle any type of request mention the type of request in the methods attribute. In this example, we are using a dictionary to store user credentials but in a real application, this would likely be stored in a database using hashing to secure the password but here we are focusing on GET and POST requests. We are handling the GET request by using the args attribute and the POST method by using the POST attribute. 

Python3




# app.py
 
from flask import Flask, render_template, request, redirect, session
 
app = Flask(__name__)
 
# Set a secret key for encrypting session data
app.secret_key = 'my_secret_key'
 
# dictionary to store user and password
users = {
    'kunal': '1234',
    'user2': 'password2'
}
 
# To render a login form
@app.route('/')
def view_form():
    return render_template('login.html')
 
# For handling get request form we can get
# the form inputs value by using args attribute.
# this values after submitting you will see in the urls.
# this exploits our credentials so that's
# why developers prefer POST request.
@app.route('/handle_get', methods=['GET'])
def handle_get():
    if request.method == 'GET':
        username = request.args['username']
        password = request.args['password']
        print(username, password)
        if username in users and users[username] == password:
            return '<h1>Welcome!!!</h1>'
        else:
            return '<h1>invalid credentials!</h1>'
    else:
        return render_template('login.html')
 
# For handling post request form we can get the form
# inputs value by using POST attribute.
# this values after submitting you will never see in the urls.
@app.route('/handle_post', methods=['POST'])
def handle_post():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        print(username, password)
        if username in users and users[username] == password:
            return '<h1>Welcome!!!</h1>'
        else:
            return '<h1>invalid credentials!</h1>'
    else:
        return render_template('login.html')
 
if __name__ == '__main__':
    app.run()


Step 4: To run the app.py file run the below command in the command prompt.

flask –app app.py –debug run

Output: In the below output we can see that when we are login through first form the username and password is visible in the URL and the user logged in because we have used GET request in the first form and when the user is login through the second form where POST request is used the username and password is not visible in the URL and user get logged in.

 

RELATED ARTICLES

Most Popular

Recent Comments