python requests get headers

Python Requests Get Headers

If you are working with APIs or web scraping, you may want to get the headers of a response using Python. Python Requests is a popular library for making HTTP requests in Python. In this blog post, I will show you how to use Python Requests to get headers.

Method 1: Using the headers attribute

You can get the headers of a response using the headers attribute of the response object. Here is an example:


import requests

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

headers = response.headers
print(headers)

In this example, we import the requests library and make a GET request to a URL. Then we use the headers attribute of the response object to get the headers and print them to the console.

Method 2: Using the get() method with the headers parameter

You can also get the headers of a response using the get() method of the requests library. Here is an example:


import requests

url = "https://www.example.com"
headers = {"User-Agent": "Mozilla/5.0"}

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

print(response.headers)

In this example, we pass a dictionary of headers to the get() method using the headers parameter. This will override any default headers that Requests would have added. We then print the headers of the response to the console.

There are many other parameters that you can pass to the get() method, such as cookies, proxies, and authentication.

Conclusion

In this blog post, we have looked at two ways to get the headers of a response using Python Requests. The first method uses the headers attribute of the response object, while the second method uses the get() method with the headers parameter. Depending on your use case, you may find one method more useful than the other.