API Navigator Logo

Sending Custom Headers with Python Requests

Author: Newtum

This example demonstrates how to add or modify HTTP headers in your requests using the Python Requests library. This is essential for tasks like authentication or specifying content types.

Why Send Custom Headers?

HTTP headers are used to pass additional information between the client and the server. Common use cases include sending an `Authorization` header with an API key or token, or a `User-Agent` header to identify your client.

How to Send Headers

You can pass a dictionary of headers to the `headers` parameter of any request method.

import requests

url = 'https://httpbin.org/headers'
my_headers = {
    'User-Agent': 'MyCoolClient/1.0',
    'Authorization': 'Bearer mysecrettoken',
    'X-Custom-Header': 'SomeValue'
}

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

print('Status Code:', response.status_code)
# httpbin.org/headers returns the request headers
print('Response JSON:', response.json())

Default Headers in a Session

If you need to send the same headers with every request, you can set them on a Session object.

import requests

s = requests.Session()
s.headers.update({'Accept': 'application/json'})

# This request and all subsequent requests from this session will have the 'Accept' header
response1 = s.get('https://httpbin.org/headers')
print(response1.json()['headers']['Accept'])

response2 = s.get('https://httpbin.org/anything')
print(response2.json()['headers']['Accept'])