set headers in python requests

Set Headers in Python Requests

If you are working with Python requests library to send HTTP requests and want to set custom headers, you can do this by passing a dictionary of headers to the headers parameter of requests methods.

Example:

import requests

url = "https://example.com"
headers = {"User-Agent": "Mozilla/5.0"}

response = requests.get(url, headers=headers)

print(response.content)

In the above example, we first import the requests library. We then define the URL we want to make a request to and set our desired header in a dictionary format. We pass this dictionary to the headers parameter of requests.get() method.

The User-Agent header specifies which browser or user agent is making the request. In this example, we are mimicking the behavior of a Mozilla Firefox browser.

After sending the request, we can access the response content using the response.content attribute.

Multiple ways to set headers:

You can also set headers in Python requests using other methods:

  • Passing headers as a string:
import requests

url = "https://example.com"
headers = "User-Agent: Mozilla/5.0"

response = requests.get(url, headers=headers)

print(response.content)

In the above code, we are passing the header as a string, separating key and value with a colon (:) and different headers with a newline (\n) character.

  • Using requests.Session() object:
import requests

headers = {"User-Agent": "Mozilla/5.0"}

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

url = "https://example.com"
response = session.get(url)

print(response.content)

In the above code, we create a requests.Session() object and update its headers with our desired header. We can then send multiple requests using this session object without having to set headers every time.

That's it! You now know how to set custom headers in Python requests for sending HTTP requests.