At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

, , , ,

How to Install Requests Library in Python

  • By Jayagopal
  • September 10, 2019
  • 109409 Views

Python web development is preferable for many developers even tough if it is one of the oldest yet leading programming languages. Python thrives to keep up with the latest technological advancements along with its desirable features. One such great feature is its substantial number of easily available libraries. All you need to do is install the libraries, and start importing them at the beginning of your code. Moreover, you can install any number of libraries to your code according to your need.
Installing a library is not that complex as it sounds. So, here is a descriptive tutorial on how to install a requests library in Python.

What is the request library?

A Request library in Python handles the HTTP calls, where it simplifies the way to send the data on HTTP request and handles the same back in response. It eases the ways to carry out the CRUD operation and other HTTP call activities, such as data scraping. There is no restriction with the data it carries, it can carry everything from header to form data, query parameters, multipart files and others.

Request Library – Installation:

Firstly, before starting with the installation process, make sure that Python and pip were installed prior to ‘request’ module installation. To install the ‘requests’ library for Python, we can use any one of the following methods:
Here is the installation procedure for different operating systems.

Linux

$ pip install requests 

In Linux, If you require root permission, use ‘sudo’. Alternatively, you can also use pipenv to install requests library, where pipenv is used to automatically manage the packages during the course of installation/uninstallation.

$ pip install pipenv

Windows

The Windows users need to navigate to the Python directory, and then install the request module as follows:

> python -m pip install requests

Mac

For MacOS, install Python through ‘Home Brew’. Thereafter, install pip and request module (which is the same as Linux installation process.)

Usage of Request Library

Once the installation part is over, you can execute the following functions with the help of request library.

1.Verify Python Installation

To verify that Python installed on the machine, try the below one:

$ python --version

If the version of Python is not returned, refer Python installation process and proceed with ‘request’ module installation process. For Python 3x, use the command python3 rather python.

$ python3 --version

We are using Python 2x in this blog for experimenting the request module installation. So, you can see this python keyword being in use throughout the article.

2. Access to Python Over Terminal

To access Python over command line, simply type python and hit enter to explore the request module (which is priorly installed)

$ python

3. Import Requests Library

Soon after the entry to the python command line, the appropriate module can be accessed through ‘import’ keyword. In our example, we import the request module for experimenting the functionality of the request module.

>>> import requests

4. To Send Request

A list of Http methods like GET, POST, PUT, PATCH, DELETE are accessible through the request module.
In the following example, a simple get request is sent and the corresponding response is recorded as follows:

>>> requests.get('https://www.example.com/')

The above request will return <Response [200]>, if successful.

5. To Parse Response

A Http status code for a request can be accessed through request module key status_code like 200, 201, 301, 404, 500, 501 etc.,

>>> response = requests.get('https://www.example.com/')
>>> response.status_code

In the above one, a successful response of 200 returned.
Further, response data of the respective request can be parsed in a variety of formats such as content, text or JSON formats.

>>> response.content

This retrieves the content of the web page requested.

>>> response.text

The above code retrieves the response as string based on header content type, explicitly custom encoding can be passed by response.encoding = ‘utf-8’ or whichever the encoding scheme is required.

>>> response.json()

Here, it returns JSON for a valid response.

Other Frequently Used Http Methods:

Examples of widely used Http methods using request module in Python is as follows:

>>> requests.get('https://httpbin.org/get')
>>> requests.post('https://httpbin.org/post', json={'python': {'library': 'requests'}})
>>> requests.put('https://httpbin.org/put', json={'key':'value'})
>>> requests.patch('https://httpbin.org/patch', json={'key':'value'})
>>> requests.delete('https://httpbin.org/delete')
>>> cmd + d (to exit) 

A key json carries the payload/body of Http call.

Here is the sample code for a little more clarity

This code sample covers quite a few use cases of request module.

# Importing Request module, which was installed prior to
import requests
# Http Methods:
response = requests.get('https://httpbin.org/get')
print (response.status_code)
response = requests.post('https://httpbin.org/post', json={'python': {'library': 'requests'}})
print (response.request.body)
response = requests.put('https://httpbin.org/put', json={'python': {'version': '2x', 'library': 'requests'}})
print (response.request.body)
response = requests.patch('https://httpbin.org/patch', json={'python': {'version': '3x', 'library': 'requests'}})
print (response.request.body)
response = requests.delete('https://httpbin.org/delete')
print (response.status_code)
# Status Codes:
for url in ['https://httpbin.org/status/200', 'https://httpbin.org/status/400', 'https://httpbin.org/status/500']:
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise exception, if applicable
    except:
        print ('Error with status code: ' + response.status_code)
    else:
        print ('Request completed successfully')

Just copy the sample code to “file-name.py”, then open the terminal and navigate to the directory where “file-name.py” resides. Now, run the following command.

$ python file-name.py

Therefore, a successful execution of code would result in use case output.
Hire best Python developers for your web development projects easily with Agira technologies. We provide you with dedicated experts who have mastered the latest technologies. Endure the fullest of outsourcing tech experts for your company. Get in touch with our experts to hire freelance python developers, offshore python developers and python web developers who can cater to your company’s requirement.
Python web development
Read more blogs related to python web development. Such as Python Vs Node.js: What To Choose & Why – A Detailed Comparison and Developing RESTful APIs with Python and Django.
[contact-form-7 404 "Not Found"]