python requests library headers

Python Requests Library Headers

If you are working with APIs or HTTP requests in Python, the Python Requests library is a popular and powerful tool to use. When making a request, you can add headers to the request to send additional information to the server.

Headers are key-value pairs that provide information such as the user agent, content type, and authorization token to the server. Here's how to add headers to your Python Requests library code:

Method 1: Passing Headers as a Dictionary

The simplest way to add headers to your request is to pass them as a dictionary:

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',
    'Content-Type': 'application/json'

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

In this example, we are passing two headers - the user agent and the content type - as a dictionary. The headers are then added to the GET request using the 'headers' parameter.

Method 2: Using the Request Headers Property

You can also add headers using the 'headers' property of the request object:

import requests

response = requests.get('')
response.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.headers['Content-Type'] = 'application/json'

In this example, we first make a request to the desired URL without any headers, and then modify the request object's headers property directly to add the desired headers.