python requests library get headers

Python Requests Library: Get Headers

If you are working with APIs, it is important to know how to extract headers from the response. In this article, we will learn how to use Python Requests library to retrieve headers from the server.

Using Python Requests Library to retrieve headers

To retrieve headers from a URL, we first need to import the Python Requests library. We can do this by running the following code:


import requests

Once we have imported the requests library, we can then use the requests.get() method to get the headers from a URL. Here is an example:


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

headers = response.headers
print(headers)

In this example, we first define a URL and then use the requests.get() method to get the headers from the server. We then print out the headers using the print() function.

The output of this code will be a dictionary containing all the headers returned by the server:

  • Content-Type
  • Content-Length
  • Server
  • Last-Modified
  • ...

Retrieving a Specific Header

Sometimes, we may only be interested in retrieving a specific header. To do this, we can use the response.headers.get() method. Here is an example:


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

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

In this example, we retrieve the Content-Type header from the server and print it out. The output should be something like:


text/html; charset=UTF-8

Conclusion

Python Requests library is a powerful tool for working with APIs. Retrieving headers from a server is an essential part of working with APIs. By using the requests.get() method, we can easily retrieve headers and use them in our applications.