add header in python post request

Adding Header in Python Post Request

If you are working with Python requests library to make HTTP requests and want to send headers along with the POST request, then you can use the headers parameter.

Method 1: Using headers parameter


import requests

url = 'http://example.com/api'

headers = {
    'Authorization': 'Bearer xxxxxxxx',
    'Content-Type': 'application/json'
}

data = {'key': 'value'}

response = requests.post(url, headers=headers, json=data)

print(response.json())

In the above code, we have defined a dictionary of headers with two key-value pairs for Authorization and Content-Type. Then we have passed this dictionary to the headers parameter of the requests.post() method along with the data we want to send in the JSON format.

Method 2: Using a dictionary for headers

You can also directly pass a dictionary of headers to the requests.post() method without defining a separate dictionary as shown below:


import requests

url = 'http://example.com/api'

headers = {
    'Authorization': 'Bearer xxxxxxxx',
    'Content-Type': 'application/json'
}

data = {'key': 'value'}

response = requests.post(url, headers=headers, json=data)

print(response.json())

In this code, we have defined a dictionary of headers and directly passed it to the headers parameter of requests.post() method. The rest of the code is the same as Method 1.

Method 3: Using a session object

If you are making multiple requests to the same domain and want to reuse headers across requests, then you can use a requests.Session() object to maintain session state and set headers for all requests made using that session object.


import requests

url = 'http://example.com/api'

headers = {
    'Authorization': 'Bearer xxxxxxxx',
    'Content-Type': 'application/json'
}

data = {'key': 'value'}

session = requests.Session()
session.headers.update(headers)

response = session.post(url, json=data)

print(response.json())

In this code, we have created a requests.Session() object and used the headers.update() method to set the headers for all requests made using that session object. We have made a POST request using the session.post() method and passed the data in JSON format. The rest of the code is the same as Method 1 and 2.

These are the three methods to add headers in Python POST request using requests library. Choose the one that suits your needs and implement it in your code.