python requests response headers

Python Requests Response Headers

When making HTTP requests using Python's requests module, the response object contains many useful properties such as the headers. The headers property contains metadata about the response that was received, such as the content type, content length, and server information.

Viewing Response Headers

To view the response headers, we can simply access the headers property of the response object. Here is an example:


import requests

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

print(response.headers)

This will output a dictionary containing all of the headers:


{
  'Date': 'Thu, 10 Dec 2020 17:59:35 GMT',
  'Content-Type': 'text/html; charset=UTF-8',
  'Transfer-Encoding': 'chunked',
  'Connection': 'keep-alive',
  'Server': 'Apache/2.4.29 (Ubuntu)',
  'X-Powered-By': 'PHP/7.2.24-0ubuntu0.18.04.7',
  'Cache-Control': 'max-age=0, no-cache'
}

Accessing Specific Headers

If we only want to access a specific header, we can use the get() method on the headers property:


import requests

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

content_type = response.headers.get('Content-Type')

print(content_type)

This will output the content type header:


text/html; charset=UTF-8

Setting Request Headers

We can also set headers for our requests using the headers parameter:


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.36'
}

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

print(response.headers)

This will send a custom User-Agent header with our request.