python requests get headers from response

hljs.highlightAll();

Python Requests Get Headers from Response

If you're working with HTTP requests in Python using the Requests library, you may need to access the response headers. The headers contain metadata about the HTTP response, including the content type, encoding, and cache control settings.

Method 1: Using the headers attribute

The simplest way to access the response headers is to use the headers attribute of the response object:


import requests

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

This will print out a dictionary of all the response headers.

Method 2: Using the get method

You can also access a specific header by using the get method on the headers dictionary:


import requests

response = requests.get("https://www.example.com")
content_type = response.headers.get('content-type')
print(content_type)
    

This will print out the value of the "Content-Type" header.

Method 3: Using the Response object's built-in methods

When you make a request with Requests, the library provides a Response object that contains the server's response to the request. This object has several built-in methods that you can use to access the headers:

  • response.headers: returns a dictionary of all the headers
  • response.headers.get('header'): returns the value of a specific header
  • response.headers.items(): returns a list of tuples with each header and its value