HTTP requests play a very important role in web development. In fact, a lot of things (e. g. all websites) wouldn’t work without them. Therefore, every web developer should know how to handle HTTP requests.
In the following, I am going to show you how to handle HTTP requests with Flask! (Complete Code)
Table of contents:
What are HTTP requests?
Clients use HTTP requests to access or change resources on a server. There are multiple HTTP methods for updating, retrieving, or deleting resources. Here’s a list of the four most common methods:
Get
The get method is used to retrieve data from a server. For example, browsers perform a get request to retrieve the site’s HTML code.
Post
Post requests are used to send information to a server to create or update resources on the server. The information is stored in the body of the request.
Put
Put is very similar to the post method. It’s also used to create or update a resource on a server. However, the difference is that put requests are idempotent. That is, sending the same put request multiple times will produce the same result. When sending the same post request multiple times, however, it will create the same resource multiple times.
Delete
The delete method is used to delete a particular resource on a server.
Preparation
Install Flask
Of course, you need to have Python and Pip installed to follow this guide. Additionally, you need to install the Flask package using Pip in order to be able to create an HTTP server.
You can do so, by running one of the following two commands in your terminal (CMD/PowerShell on Windows):
pip install flask
OR
python -m pip install flask
Set up a Flask development server
Before we can handle requests using Flask, we need to set up a Flask server, to which we can send the requests.
Luckily, creating a Flask development server isn’t complicated and only requires four lines of code:
from flask import Flask, request, abort
app = Flask(__name__)
if __name__ == "__main__":
app.run(host="127.0.0.1") # Change this to your actual IP address
If you want to receive requests from different devices, you should change the localhost address to the actual IP address of your device. Also, you can change the port the server is listening on by adding the port parameter to the run function (e. g. app.run(host=’127.0.0.1′, port=4545)).
How to handle requests with Flask
To handle specific requests, we need to add a route and specify which methods are accepted on that route. If we want to accept multiple methods, we have to check for the method that’s been used and run the corresponding block of code.
@app.route('/get-and-post', methods=['POST', 'GET']) # Specify the route and the accepted methods
def get_and_post():
if request.method == 'POST': # Check if the used methods is a post request
# Specify what should happen with the post requests
return 'success (POST)', 200
elif request.method == 'GET': # Check whether the used method is a get request
# Specify what should happen with the get request
return 'success (GET)', 200 # response message and code
else:
abort(400)
To make it work, we simply need to add this snippet of code to the code from the preparation part.
If we now access ‘http://[your-ip-address]:5000/get-and-post‘ using the browser, we should see this message: success (GET)
If we send a post request to ‘http://[your-ip-address]:5000/get-and-post‘, we should receive ‘success (POST)‘.
Of course, you can also specify multiple functions for multiple requests.
How to access the request's arguments?
Luckily, accessing the arguments of a request isn’t complicated at all:
@app.route('/get', methods=['GET'])
def get():
print(request.args) # print all arguments
print(request.args.get('[arg_name]')) # print the value of a specific argument
Flask requests - Full example code
Here’s a complete example code that you can copy & paste and build up upon:
from flask import Flask, request, abort
app = Flask(__name__)
@app.route('/post', methods=['POST'])
def webhook(): # Handle post requests
if request.method == 'POST':
print(request.json) # print some information about the request
print('Post request received')
return 'success', 200
else:
abort(400)
@app.route('/get', methods=['GET'])
def get(): # Handle get requests
if request.method == 'GET':
print(request.json)
print(request.args) # print all arguments
return '<h1>Today is {}</h1>'.format(request.args.get('Day')), 200 # access a specific argument
else:
abort(400)
if __name__ == "__main__":
app.run(host="192.168.178.73") # Change this to your IP address
Happy coding, and thanks for reading!