Making GET HTTP Requests with Python Flask

Learn about generating and making GET HTTP Requests with Python Flask and parse the JSON response in Raspberry Pi or web server. GET method is the type of HTTP request method used to request data from the server or send data to the server. For this are going to use certain inbuilt Python libraries. We are going to Import the ‘Request’ and ‘JSON’ library in our Python code. So, let’s start.

Installing Requests in Python pip

To generate a GET request you will have to import the Requests library. To install the Request library, use the following command.
pip install requests

Generating GET Request

Create a python file that imports ‘requests’ and ‘JSON’. request.get() method is used to generate a GET request. This method has can contain parameters of URL, params, headers and basic authentication. URL is the location for sending the request. Params are the list of parameters for the request.

Code for Simple GET request for the following URL is as below “www.example.com/index.php”

r = request.get('http://example.com/index.php')

To send the request containing parameters

r = requests.get('http://example.com/index.php', params={'q': 'raspberry pi request'})

To send the request containing headers

r = requests.get('http://example.com/index.php', headers={'X-Platform': 'RaspberryPi'})

If the GET request requires basic authentication, a request will be as below

r = requests.get('http://google.com/index.php', auth=('username', 'password'))</code

Here ‘r’ is an object of response. Now, parse the JSON Response and get the values.


Parsing JSON Response of Request

For the response to be in JSON format, we are going to change the response type to JSON. To do this, we will change the response type and store it in a variable.

data = r.json()

The ‘data’ variable stores the parsed JSON response. The JSON response is nothing but a raw response in the ‘python dictionary’ format. For extracting data from JSON response, use a similar method as you would access data stored in the dictionary.

Extracting data from JSON
example = data["value1"]["value2"]

This will return the value of that object parameter. To Print the received data:
print(example)

We sent a GET request to www.example.com with certain parameters and we converted the response in JSON format. Now, we extracted information from the JSON and print the extracted response.

Code for generating GET HTTP Requests with Python

This is full code for generating GET HTTP Request with python on example.com with parameters

This is how Generating GET requests and parsing JSON response works.

Flask web server can be also used for request-response. Learn more about Requests from python-requests.org

Leave a Reply