what is requests library in python

What is Requests library in Python?

Requests is a Python package that allows you to send HTTP/1.1 requests extremely easily. This package simplifies making HTTP requests in Python by handling the underlying networking and caching.

Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode your POST data. You can also add custom headers, authentication, and other request parameters using this package.

The package is simple to use, with a consistent API for all methods. It also has powerful response handling features, including automatic decoding of JSON/XML responses, and automatic content negotiation.

Installation

You can install Requests using pip, which is a package manager for Python packages. Simply run the following command in your terminal:


    pip install requests
    

Sending a Request with Requests

Sending a request using Requests is very easy. You simply call the method of the request type you want, and pass the URL as the first argument.


    import requests

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

In the above code, we’re sending a GET request to the URL ‘https://www.example.com’. The response from this request is stored in the ‘r’ variable. We can then access the content of the response by calling ‘r.content’.

HTTP Methods

Requests supports all major HTTP methods, including GET, POST, PUT, DELETE, HEAD, OPTIONS, and PATCH. To send a request using one of these methods, simply use the corresponding method of the requests module.


    import requests

    # GET request
    r = requests.get('https://www.example.com')

    # POST request
    data = {'key': 'value'}
    r = requests.post('https://www.example.com', data=data)

    # PUT request
    data = {'key': 'new_value'}
    r = requests.put('https://www.example.com', data=data)

    # DELETE request
    r = requests.delete('https://www.example.com')
    

HTTP Headers

You can add custom headers to your requests using the ‘headers’ parameter. This is useful if you need to set headers such as ‘User-Agent’, ‘Accept-Encoding’, or ‘Authorization’.


    import requests

    headers = {'User-Agent': 'Mozilla/5.0'}
    r = requests.get('https://www.example.com', headers=headers)
    

HTTP Authentication

Requests supports HTTP authentication out of the box. You can send basic authentication credentials by passing a tuple of the form (username, password) to the ‘auth’ parameter.


    import requests

    auth = ('username', 'password')
    r = requests.get('https://www.example.com', auth=auth)