How to Perform an HTTP GET Request in Python using the http.client Module
In this article, we show how to perform a GET request in Python using the http.client module.
The http.client module is a module that uses the HTTP protocol to achieve different tasks.
The HTTP protocol is how servers on the internet communicate with each other so that information such as web pages on the web can be retrieved.
A GET request is a request that uses the HTTP protocol that retrieves data from the internet. It is designed to get data, such as all the content from a web page.
So, in this example, we will do a GET request that retrieves the content of this website's home page.
Using the following code below, we are able to do this.
Let's now go over this code.
First, we import the http.client module, so that we can use its functionality.
We then create a variable, h, which stores the connection to the server that hosts the website, www.learningaboutelectronics.com, specifically the home page, in this case. If we wanted to access another page, we specify the path to that page. In this case, we are simply going to retrieve the content on the home page of the website.
On this variable, h, we perform a GET request, which allows us to retrieve information from this web page.
We then create a variable, data, which allows us to get basically all the data that is on the home page of www.learningaboutelectronics.com
We retrieve all contents of the page and store it in this variable, data
data.code is the response that is returned by the server for this request that is made. Running this code, you should get an HTTP response of 200, which means that the request succeeded or was successful.
Next, we print the headers of a web page, using the statement, data.headers
The header includes things such as the date, the content-type of the page, etc.
Next we create a variable, text, that stores all the text on the page using the readlines() function.
To print out the text, we then use a for loop and decode it it using the utf-8 format.
After running this code, we get the following output shown below.