add headers in python requests

Adding Headers in Python Requests

If you want to send additional information with your HTTP request, headers are a great way to do it. In Python Requests, you can add headers to your request by passing a dictionary of headers to the headers parameter.

Example:


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.text)

In the above example, we have created a dictionary of headers containing two keys: User-Agent and Accept-Language. The User-Agent header specifies the browser user agent string to identify the client making the request, and the Accept-Language header specifies the preferred language for the response.

We then pass this dictionary of headers to the headers parameter of the get() function, which sends the GET request to the specified URL.

Multiple Ways to Add Headers:

In addition to passing a dictionary of headers to the headers parameter, there are multiple ways to add headers in Python Requests:

  • You can set a default header for all requests by using the headers parameter of the Session object.
  • You can add or modify headers for a specific request by using the request object's headers attribute.
  • You can also pass headers as a list of tuples to the headers parameter.

Here is an example of setting a default header:


import requests

session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'})

response = session.get('https://www.example.com')

print(response.text)

In the above example, we have created a Session object and set the User-Agent header as the default header for all requests made through this session.

Here is an example of adding or modifying headers for a specific request:


import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    'Custom-Header': 'Custom Value'
}

response = requests.get('https://www.example.com', headers=headers)
response.headers['Custom-Header'] = 'New Value'

print(response.text)

In the above example, we have added a custom header to the request and modified its value after receiving the response.

Lastly, here is an example of passing headers as a list of tuples:


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.text)

In the above example, we have passed headers as a list of tuples to the headers parameter of the get() function.

Using headers in Python Requests is a great way to add additional information to your HTTP request and get the response you need from the server. With multiple ways to add headers, you can choose the method that works best for your needs.