Pass multiple headers in Python Requests
If you are working with APIs or web services, you may need to include multiple headers in your HTTP requests. In Python, you can achieve this by using the Requests library.
Method 1: Pass headers as a dictionary
The simplest way to pass multiple headers in a request is to define them as a dictionary and pass it as the headers parameter:
import requests
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept-Language': 'en-US,en;q=0.5'
}
response = requests.get('https://example.com', headers=headers)
In this example, we define two headers: User-Agent and Accept-Language. We then pass the headers dictionary as the headers parameter in the GET request to example.com.
Method 2: Pass headers as keyword arguments
You can also pass headers as keyword arguments:
import requests
response = requests.get('https://example.com',
headers={'User-Agent': 'Mozilla/5.0',
'Accept-Language': 'en-US,en;q=0.5'})
This method is useful if you only need to pass a few headers and don't want to define a separate dictionary.
Method 3: Use Session object
If you need to pass the same headers to multiple requests, it's more efficient to use a Session object:
import requests
s = requests.Session()
s.headers.update({'User-Agent': 'Mozilla/5.0', 'Accept-Language': 'en-US,en;q=0.5'})
response1 = s.get('https://example.com/page1')
response2 = s.get('https://example.com/page2')
In this example, we create a Session object and define two headers. We then use the same Session object to make two GET requests to example.com. The same headers will be included in both requests.