Python Requests Module
The python requests module is useful to perform the HTTP requests like GET, POST, DELETE, etc., to get/post data to the specified URL.
Before you start using the requests module, you need to install the requests module in the PIP location. To download and install the requests module, open your command prompt, and navigate your PIP location and type the pip install requests command.
After completion of installing the requests module, your command-line interface will be as shown below.
If you already open the python interpreter, close it and reopen the interpreter to sync with the latest changes. After installing the requests module, you can use it in your applications by importing the requests module, as shown below.
Following is the example of using the requests module to send the HTTP GET request to the specified URL in python.
result = requests.get('https://api.github.com')
if result.status_code == 200:
print('Success')
elif result.status_code == 404:
print('Not Found')
The above requests module example will print the response based on the result object that we received from the HTTP request.
When you execute the above python example, it will return the result as shown below.
The response object that we received from the HTTP request will have different properties/methods like status_code, content, text, etc., to perform different operations based on our requirements.
Like the HTTP GET method, the request module has different methods to perform HTTP operations based on your requirements.
Following is the example of using the different HTTP methods in the requests module.
r1 = rq.get('https://api.github.com/search/repositories', params={'q': 'requests+language:python'})
print(r1)
r2 = rq.post('https://httpbin.org/post', data={'key':'value'})
print(r2)
r3 = rq.put('https://httpbin.org/put', data={'key':'value'})
print(r3)
r4 = rq.delete('https://httpbin.org/delete')
print(r4)
r5 = rq.head('https://httpbin.org/get')
print(r5)
r6 = rq.patch('https://httpbin.org/patch', data={'key':'value'})
print(r6)
r7 = rq.options('https://httpbin.org/get')
print(r7)
The HTTP GET method will send the parameters in the query string using the params parameter. The POST, PUT, and PATCH methods will send the payload through the message body using data parameters.
This is how you can use the requests module in python to get the required data from other URLs using HTTP methods such as GET, POST, PUT, PATCH, etc., based on your requirements.
