Python Requests: GET Headers

GET Headers

GET headers are the key-value pairs sent by the web browser to the server when sending a GET request. These headers contain information about the request and the client making it.

In Python, we can access these headers by using the requests library. The requests library allows us to send HTTP requests and handle responses easily. By default, the library sends a set of headers with every request, but we can also customize the headers to meet our needs.

Send GET Request with Custom Headers

When sending a GET request with custom headers, we can use the headers parameter of the requests.get() method to specify our custom headers.

Example


import requests

url = 'https://httpbin.org/headers'

custom_headers = {

    'User-Agent': 'my-app',

    'Authorization': 'Bearer my_token',

}

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

print(response.json())

Output


{

  "headers": {

    "User-Agent": "my-app",

    "Authorization": "Bearer my_token"

  }

}

Access Response Headers

We can access the headers of a response object by using the headers attribute. This attribute returns a dictionary-like object containing the response headers.

Example


import requests

url = 'https://httpbin.org/get'

response = requests.get(url)

print(response.headers)

Output


{

  "Accept-Encoding": "gzip",

  "Content-Length": "247",

  "Content-Type": "application/json",

  "Date": "Mon, 16 Oct 2023 06:06:20 GMT",

  "Server": "nginx",

  "Via": "1.1 vegur"

}

Access Specific Response Header

To access a specific header from the response, we can use the get() method of the headers dictionary-like object. We can also use square brackets to access a specific header, but using get() is safer as it returns None if the header is not found instead of raising a KeyError.

Example

Accessing Content-Length Header:


import requests

url = 'https://httpbin.org/get'

response = requests.get(url)

content_length = response.headers.get('Content-Length')

print(content_length)

Output


247

Conclusion

In this article, we learned how to send GET requests with custom headers and access response headers using the Python Requests library. Custom headers can be sent using the headers parameter of the requests.get() method, and response headers can be accessed using the headers attribute of the response object. We can also access specific headers using the get() method to avoid KeyErrors.

Scroll to Top