python requests headers

Python Requests Headers

Headers are the additional information sent along with the HTTP request or response. In Python Requests library, headers can be passed as a dictionary to the header parameter of requests.get() or requests.post() methods.

Here is an example:


import requests

url = 'https://www.example.com'
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.36'}
response = requests.get(url, headers=headers)

In the above example, the User-Agent header is added to the GET request. The User-Agent header provides information about the browser or client making the request. In this case, we are pretending to be a Chrome browser on a Windows machine.

Multiple Ways to Set Headers

There are multiple ways to set headers in Python Requests library:

  • Passing headers as a dictionary to the headers parameter of requests.get() or requests.post() methods.
  • Using the add_header() method of request object.

Here is an example of using the add_header() method:


import requests

url = 'https://www.example.com'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
request = requests.Request('GET', url)
request.add_header('User-Agent', headers['User-Agent'])
prepared_request = request.prepare()
response = requests.Session().send(prepared_request)

In the above example, we are creating a request object using the Request class and then adding the User-Agent header using the add_header() method. The prepared request is then sent using the Session object.

Conclusion

Headers are an important part of HTTP requests and responses. Python Requests library provides an easy way to set headers using dictionaries or the add_header() method.