Python Requests Post Multiple Headers
In Python, we can use the Requests module to send HTTP requests using Python. With Requests, we can easily send POST requests to a website and pass data in the request headers. Headers are pieces of metadata that are sent along with the request to provide additional information about the request or to identify the sender.
To send multiple headers in a POST request, we can use the headers
parameter in the post()
method of the Requests module. The headers
parameter is a dictionary containing key-value pairs of header names and values.
Example:
import requests
url = 'https://example.com'
headers = {
'Content-Type': 'application/json',
'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'
}
data = {
'key1': 'value1',
'key2': 'value2'
}
response = requests.post(url, headers=headers, json=data)
print(response.status_code)
print(response.content)
In this example, we are sending a POST request to https://example.com
with two headers: Content-Type
and User-Agent
. We are also passing data in JSON format using the json
parameter.
We can also add headers to a Session object in Requests, which will apply to all requests sent using that Session:
Example:
import requests
url = 'https://example.com'
headers = {
'Content-Type': 'application/json',
'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'
}
data = {
'key1': 'value1',
'key2': 'value2'
}
session = requests.Session()
session.headers.update(headers)
response = session.post(url, json=data)
print(response.status_code)
print(response.content)
In this example, we are creating a Session object and setting the headers using the headers.update()
method. We are then sending a POST request using the post()
method of the Session object.
These are the two ways we can send multiple headers in a POST request using Python Requests module.