How to Add Multiple Headers in Python Requests
Python requests is a popular library for sending HTTP requests in Python. Sometimes, you may need to add multiple headers to a request for various reasons, such as to authenticate, set content type, or add custom headers. In this article, we will explore different ways to add multiple headers in Python requests.
Using a Dictionary
The most common way to add multiple headers to a request is by using a dictionary object. The keys of the dictionary represent the header names, and the values represent the header values. Here's an example:
import requests
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ',
'Custom-Header': 'Custom Value'
}
response = requests.get('https://api.example.com', headers=headers)
In this example, we create a dictionary called `headers` that contains three headers: `Content-Type`, `Authorization`, and `Custom-Header`. We then pass this dictionary to the `headers` parameter of the `requests.get()` method.
Using a List of Tuples
You can also add multiple headers by using a list of tuples. Each tuple contains two elements: the header name and the header value. Here's an example:
import requests
headers = [
('Content-Type', 'application/json'),
('Authorization', 'Bearer '),
('Custom-Header', 'Custom Value')
]
response = requests.get('https://api.example.com', headers=headers)
In this example, we create a list called `headers` that contains three tuples, each representing a header. We then pass this list to the `headers` parameter of the `requests.get()` method.
Combining Headers
If you need to add headers to a request that already has headers, you can combine the existing headers with your new headers by using the `update()` method on the dictionary object. Here's an example:
import requests
existing_headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer '
}
new_headers = {
'Custom-Header': 'Custom Value'
}
headers = existing_headers.copy()
headers.update(new_headers)
response = requests.get('https://api.example.com', headers=headers)
In this example, we create two dictionaries: `existing_headers` and `new_headers`. We then combine them by creating a new dictionary called `headers`, copying `existing_headers` and then using `update()` method to add `new_headers`. We then pass this combined dictionary to the `headers` parameter of the `requests.get()` method.
Conclusion
There are several ways to add multiple headers to a Python requests. Using a dictionary or a list of tuples are the most common methods. If you need to combine existing headers with new headers, use the `update()` method on the dictionary object.