Requests is a Python library, used for all kinds of HTTP requests. It is developed by Kenneth Reitz and released under Apache2 license. The goal of this project is to make http requests simpler and more human friendly.
Request was developed with below PEP 20 idioms in mind.
Requests is one of the most downloaded Python packages of all time.
Simplest method to install requests is by using pip. In Windows, pip is available under "script" directory and in linux under "bin" directory of Python's installation path.
pip install requests
Let us now see how we can use requests for GET and POST calls.
requests library.requests module to make http GET request .import requests
http://httpbin.org/get in a variable. (In below example, I have stored the URL in url variable).url = "http://httpbin.org/get"
url variable to the get() function in requests library and store the result in a variable. (I have store the result in a variable r)r = requests.get(url)
status_code to fetch the http return code. If the request was successful, the return code is 200 .r.status_code
headers to fetch header of the request.r.headers
text to fetch the output in text format.r.text
json() to fetch the output in json format.r.json()
In above code I have used time.sleep(2) to wait for 2 sec before each result is displayed.
Dictionary is {'language': 'python', 'library': 'requests'}
payload variable.payload = {'language': 'python', 'library': 'requests'}
params, in the get function to pass the above dictionary as a parameter.r = requests.get(url, params=payload)
url.print("URL: {} \n".format(r.url))
args. To fetch it value, convert the output of request to json and fetch the value of args variable.print("Json Output: {}".format(r.json()['args']))
Note: Since this is a GET request, the passed parameters are visible in URL.
Dictionary is {'language': 'python', 'library': 'requests'}
values variable).values = {'language': 'python', 'library': 'requests'}
post() function.r = requests.post('http://httpbin.org/post', data=values)
Similar to example 1, we have use time library to delay the output by 2 sec.
Note: Since this is a POST request, the passed parameter is not visible in the URL.
The python's requests library is a very handy tool when trying to scrape some webpages for information or developing tools using rest API. We can also download music files, wallpapers, etc from different websites once we have the URL.
If you have any questions, comments or have used Requests before, I'd would love to hear from you in comment section.