python requests library with headers

Python Requests Library with Headers

Python Requests is a popular and powerful HTTP library used for sending HTTP requests in Python. It simplifies the process of sending HTTP requests and handling responses. The library supports various HTTP methods such as GET, POST, PUT, DELETE, PATCH, etc.

Headers are an important part of HTTP requests and responses. Headers contain additional information about the request or response in the form of key-value pairs. The headers can be used to provide authentication information, content type, user agent, and many other things.

Using Python Requests with Headers

Headers can be added to a request by passing them as a dictionary to the headers parameter in the request function. Here is an example of how to add headers to a request:


import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}

response = requests.get('https://www.example.com', headers=headers)

print(response.text)

In this example, we have added a User-Agent header to the request to identify the client software making the request.

Multiple Headers

You can add multiple headers to a request by adding multiple key-value pairs in the headers dictionary. Here is an example:


import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
    'Authorization': 'Bearer your_token_here'
}

response = requests.get('https://www.example.com', headers=headers)

print(response.text)

In this example, we have added two headers - User-Agent and Authorization.