Flask HTTP Methods

In this article, we will explore the different Flask HTTP methods and how to use them in your web applications with examples.

The HTTP protocol forms the basis of data communication on the internet and provides various methods of obtaining data from a particular URL.

HTTP methods specify the type of request being sent to the server and are commonly used, including GET, POST, PUT, DELETE and HEAD.

Each method serves a specific purpose and can be utilized for a range of operations on the server.

MethodsOverview
GETThe most widely used method involves sending data to the server without any encryption
HEADSimilar to the GET method, except that it doesn’t include a response body.
POSTThis method is employed to send HTML form data to the server, and unlike other methods, the data received by the POST method is not cached by the server.
PUTThis method substitutes all present representations of the designated resource with the content that has been uploaded.
DELETEThis method eliminates all present representations of the resource identified by a URL.


GET Method

The GET method is used to ask the server to give data.

When someone sends a GET request, the server gets the data and sends it back to the person who requested it.

The GET method is mostly used to get information from databases or other places where information is stored.

In Flask, the GET method can be used with the @app.route decorator.

Example: 

from flask import Flaskapp = Flask(__name__)@app.route('/') def hello_world(): return 'Hello, World!'if __name__ == '__main__': app.run()

POST Method

The POST method is used to give data to the server.

When someone sends a POST request, the server takes the data and processes it.

The POST method is often used for adding new information to a database or updating existing information.

In Flask, the POST method uses the request.form attribute.

Example: 

from flask import Flask, requestapp = Flask(__name__)@app.route('/login', methods=['POST']) def login(): username = request.form['username'] password = request.form['password'] # perform authentication here return 'Logged in successfully!'if __name__ == '__main__': app.run()

PUT Method

The PUT method is used to update information that is already stored on the server.

When someone sends a PUT request, the server takes the data and changes the specified information.

In Flask, the PUT method uses the request.form attribute.

Example: 

from flask import Flask, requestapp = Flask(__name__)@app.route('/user/<int:user_id>', methods=['PUT']) def update_user(user_id): # update user data in the database here return f'User {user_id} updated successfully!'if __name__ == '__main__': app.run()

DELETE Method

The DELETE method is used to remove information from the server.

When someone sends a DELETE request, the server finds the information and removes it.

In Flask, the DELETE method uses the request.form attribute.

Example: 

from flask import Flask, requestapp = Flask(__name__)@app.route('/user/<int:user_id>', methods=['DELETE']) def delete_user(user_id): # delete user data from the database here return f'User {user_id} deleted successfully!'if __name__ == '__main__': app.run()

HEAD Method

The HEAD method is similar to the GET method, but it only returns the headers of the response without the actual content.

This is helpful when you need to check if a resource exists or if it has been changed without downloading the whole resource.

In Flask, the HEAD method uses the @app.route decorator.

By default, the Flask route is set up to respond to GET requests, but it can be changed by passing a method argument to the route() decorator.

To illustrate the usage of POST method in URL routing, we will begin by designing an HTML form and utilizing the POST method to send the form data to a URL.

Make a simple form with html and name the file form.html:

Example: 

<html> <body> <form action = "http://localhost:5000/form" method = "post"> <label for="nm">Name: </label> <input type = "text" name = "nm" /><label for="pw">Password: </label> <input type = "password" name = "pw" /><input type = "submit" value = "submit" /> </form> </body> </html>

You can now input the following program code into the Python shell.

Example: 

from flask import Flask, redirect, url_for,request app = Flask(__name__)@app.route('/display/<name>/<password>') def submit(name, password): return f'Name: {name}, Password: {password}'@app.route('/form/',methods = ['GET','POST']) def form(): if request.method == 'POST': nm = request.form['nm'] pw = request.form['pw'] return redirect(url_for('submit', name = nm, password = pw)) else: nm = request.args.get('nm') pw = request.args.get('pw') return redirect(url_for('submit', name = nm, password = pw)) if __name__ == '__main__': app.run(debug = True)

Once you start the development server, open the “form.html” file in your web browser.

Type in your name in the blank space provided on the page, and then click on the “Submit” button. This will send the data you entered to the URL specified in the “action” attribute of the HTML form tag.

In this case, the URL is “http://localhost/form“, which is connected to the “form()” function. Since the data is being sent through the POST method, the values of the “nm” and “pw” parameters in the form data can be retrieved.

nm = request.form['nm']
pw = request.form['pw']

The variable part is sent to the URL “/submit“. As a result, the web browser shows a window with a field for entering a name and a password.

Modify the “method” parameter in the “form.html” file to “GET“, and then reopen the file in your web browser.

This time, the data sent to the server will be returned through the GET method. The values of the “nm” and “pw” parameters can now be computed utilizing this method.

nm = request.args.get('nm')
pw = request.args.get('pw')

In this scenario, “args” is a dictionary object that holds a set of pairs of form parameters and their respective values.

The value that belongs to the “nm” and “pw” parameters is sent to the “/submit” URL just like before.

Take the calculator example of HTTP methods which provide the sum of two numbers.

First make form.html file:

Example: 

<html> <body> <h1>CALCULATOR</h1> <form action = "http://localhost:5000/form" method = "post"> <label for="num1">First value: </label> <input type = "number" name = "num1" /><label for="num2">Second Value: </label> <input type = "number" name = "num2" /><input type = "submit" value = "Add" /> </form> </body> </html>

In a python shell run the below code:

Example: 

from flask import Flask, redirect, url_for,request app = Flask(__name__)@app.route('/sum/<int:num1>/<int:num2>') def submit(num1, num2): return f'Sum of {num1} and {num2}: {num1+num2}'@app.route('/form/',methods = ['GET','POST']) def form(): if request.method == 'POST': n1 = request.form['num1'] n2 = request.form['num2'] return redirect(url_for('submit', num1 = n1, num2 = n2)) else: n1 = request.args.get('num1') n2 = request.args.get('num2') return redirect(url_for('submit', num1 = n1, num2 = n2)) if __name__ == '__main__': app.run(debug = True)

Above Example Explanation

  • The code is an example of a Flask application that performs basic arithmetic operations.
  • The application has two routes: “/sum” and “/form“.
  • The “/sum” route accepts two integer parameters, “num1” and “num2”, which are passed as part of the URL. When this route is accessed, it returns the sum of “num1” and “num2“.
  • The “/form” route accepts both GET and POST requests.
  • When the “/form” route is accessed using the POST method, the values of “num1” and “num2” are obtained from the submitted form data.
  • The route then redirects to the “/sum” route with the values of “num1” and “num2” passed as parameters.
  • When the “/form” route is accessed using the GET method, the values of “num1” and “num2” are obtained from the query parameters in the URL.
  • Again, the route redirects to the “/sum” route with the values of “num1” and “num2” passed as parameters.
  • Finally, the “if name == ‘main‘:” statement is used to start the Flask application in debug mode when the script is run directly.

Flask HTTP Methods Benefits

The following are some advantages of utilizing Flask HTTP methods:

  • Flask empowers you to set HTTP methods for specific routes, which can improve security by only permitting authorized methods to access certain routes.
  • You can take advantage of Flask’s flexibility to define custom HTTP methods, which can assist you in constructing more intricate web applications that necessitate more specific functionality.
  • Flask HTTP methods are straightforward for you to use and comprehend, making it easier for you to create web applications that are simple to maintain and update.
  • You can enhance performance by utilizing Flask HTTP methods, which allow you to use the appropriate method for each task, reducing the number of unnecessary requests and responses.
  • Flask HTTP methods can help you write cleaner code by separating the logic of each method and making it easier for you to comprehend and debug.

Conclusion

As a developer, you can take advantage of Flask’s support for a variety of HTTP methods, which offers several advantages. These benefits include improved security, flexibility, simplicity, better performance, and easier maintenance of the code. With the availability of Flask HTTP methods, you can create web applications that are secure, effective, and manageable, making it a well-liked option for your web development initiatives.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *