python requests library response headers

Python Requests Library Response Headers

When making HTTP requests to a server using the Python Requests library, it is possible to retrieve response headers in addition to the response body. Response headers contain metadata about the response, such as the content type, encoding, and caching directives.

Retrieving Response Headers

To retrieve the response headers from a request made with Python Requests, you can access the headers attribute of the response object:

import requests

response = requests.get('http://example.com')
headers = response.headers

print(headers)

The above code will output a dictionary containing all of the response headers:

  • Content-Type: The media type of the response body (e.g. "text/html")
  • Content-Length: The length of the response body in bytes
  • Date: The date and time that the response was sent by the server
  • Server: The name and version of the server software
  • ...

Accessing Specific Headers

If you only need to access a specific header from the response, you can use the get() method of the headers dictionary:

import requests

response = requests.get('http://example.com')
content_type = response.headers.get('Content-Type')

print(content_type)

The above code will output the value of the Content-Type header (e.g. "text/html").

Multiple Ways to Access Headers

There are multiple ways to access response headers in Python Requests, including:

  • Using the headers attribute of the response object to retrieve all headers
  • Using the get() method of the headers dictionary to retrieve a specific header
  • Using the raw attribute of the response object to access the raw HTTP response, including headers and body
import requests

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

# Method 1: Retrieve all headers
headers = response.headers

# Method 2: Retrieve a specific header
content_type = response.headers.get('Content-Type')

# Method 3: Access the raw HTTP response
raw_response = response.raw

It is recommended to use the first or second method for most use cases, as the third method requires additional parsing of the raw HTTP data.