how to add headers in python requests

How to Add Headers in Python Requests

If you're using Python requests library, adding headers to your HTTP request allows you to send additional information, such as authentication credentials or user-agent strings, with your request. Here are a few ways to add headers in Python requests:

Method 1: Using the headers parameter

The easiest and most straightforward way to add headers in Python requests is by using the headers parameter. Here's an example:


import requests

headers = {
    "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"
}

response = requests.get("https://www.example.com", headers=headers)

In the above code snippet, we're using the headers parameter to pass a dictionary of headers to the requests.get() method. The header we're passing is a user-agent string, which tells the server what type of web browser we're using.

Method 2: Using a dictionary

You can also add headers by creating a dictionary of headers and passing it directly to the requests.get() method. Here's an example:


import requests

headers = {
    "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"
}

response = requests.get("https://www.example.com", headers=headers)

Just like in method 1, we're passing a user-agent string as a header in this example. However, instead of using the headers parameter, we're passing the dictionary of headers directly to the requests.get() method.

Method 3: Using a session object

If you're making multiple requests to the same server and want to reuse the same headers across all of them, you can use a session object to add headers. Here's an example:


import requests

headers = {
    "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"
}

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

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

In this example, we're creating a session object and using the update() method to add headers to the session object. We're then making a GET request using the session object with the headers already included.

These are three ways you can add headers in Python requests. Choose the one that makes the most sense for your use case and get started!