Site icon Iotguider

Making POST HTTP Requests with Python Flask

Making POST HTTP Requests with Python in Raspberry Pi

Learn about generating and making POST HTTP Requests with Python Flask and parse the JSON response in Raspberry Pi or web server. The POST 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 POST request you will have to import the Requests library. To install the Request library, use the following command.
pip install requests

Generating POST Request

Create a python file that imports ‘requests’ and ‘JSON’. request.post() method is used to generate a POST 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 POST request for the following URL is as below “www.example.com/index.php”

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

To send the request containing parameters

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

To send the request containing headers

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

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

r = requests.post('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 POST 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 POST HTTP Requests with Python

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



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

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

Exit mobile version