how to pass headers in python requests

How to Pass Headers in Python Requests

Passing headers in Python Requests is a common task that many developers perform. Headers are used to provide additional information to the server when making HTTP requests.

Method 1: Passing Headers as a Dictionary

The simplest and most common way to pass headers in Python Requests is by passing a dictionary of headers as an argument.


import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    'Accept-Language': 'en-US,en;q=0.5'
}

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

print(response.content)

In the code above, we are passing two headers: User-Agent and Accept-Language as a dictionary to the request. Note that the headers are case-insensitive and the key can be any case.

Method 2: Using the headers Parameter

Another way to pass headers in Python Requests is by using the headers parameter directly on the request.


import requests

response = requests.get('https://www.example.com', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)','Accept-Language': 'en-US,en;q=0.5'})

print(response.content)

The code above is equivalent to the first example, but instead of passing the headers as a dictionary to the get() method, we are passing it as a parameter directly.

Method 3: Using Session Objects

If you need to make multiple requests with the same headers, you can use session objects to persist headers across requests.


import requests

session = requests.Session()

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    'Accept-Language': 'en-US,en;q=0.5'
}

session.headers.update(headers)

response1 = session.get('https://www.example.com/page1')
response2 = session.get('https://www.example.com/page2')

In the code above, we are creating a session object and updating the headers property with our headers. Then, we are using the session object to make multiple requests. The headers will be persisted across all requests made with the session object.

Conclusion

Python Requests is a powerful library for making HTTP requests, and passing headers is an essential aspect of making requests. By using one of these methods, you can easily pass headers in your Python Requests code.