The objective of this post is to explain how to do HTTP POST requests using Python and the Requests library.
Introduction
The objective of this post is to explain how to do HTTP POST requests using Python and the Requests library.
The simplest way to install this library is by using pip, as can be seen in the installation page of the library.
You can check the API description for this library here.
POST Request
The code for this tutorial will be very simple and similar to the one explained in the previous post about making HTTP GET requests from Python.
We will again use the jsonplaceholder website, which has a fake online REST API for testing and prototyping [1].
So, we start by importing the Requests library with the line of code shown bellow.
import requests
Then, we call the post method defined in this module. This method receives as argument the URL where we want to make the POST request.
response = requests.post(‘http://jsonplaceholder.typicode.com/users’)
The returning value of this invocation will be a Response object, which has some methods available, as can be seen here.
To print the response text of our request we just call the text property on the Response object, as shown bellow. The code for this property can be seen here.
print response.text
Additionally, to check the HTTP status code returned by the server, we can access the status_code attribute of the object, as shown bellow.
print response.status_code
Important: In order for WordPress to not escape the single quote in the end of URLs, I used a special character single quote. When copying and running the code, we need to change the single quote at the end of the URL to a regular one (just delete this and put a regular one). Otherwise, an error will occur and the code will not execute.
Final result
Upon running the code, we should get an output similar to the one in figure 1. As can be seen, it returns a response in JSON with an ID equal to 11. This represents the creation of a new object in the server, which is coherent with the 201 HTTP response status, which means the request has been fulfilled and has resulted in one or more new resources being created [2].
Figure 1 – Output of the Python script upon running in IDLE’s console.
Keep in mind that we are sending requests to a fake REST API created for testing purposes. So, no object is being created in the server and thus, if we run the code again, it will output the creation of an object with exactly the same ID.
References
[1] http://jsonplaceholder.typicode.com/
[2] https://httpstatuses.com/201
Related Posts
Technical details
- Python version:2.7.8
- Requests library: 2.11.1
Pingback: Python: Parsing JSON | techtutorialsx
Pingback: Python: Parsing JSON | techtutorialsx