The Python Requests library provides a straightforward way to set custom headers in your HTTP requests. This is particularly useful when you need to interact with APIs that require specific headers, such as authentication tokens, content types, or other metadata.
The most common way to set custom headers in a Requests call is by using the headers
parameter. This parameter accepts a dictionary, where the keys are the header names and the values are the corresponding header values.
import requests
url = "https://api.example.com/endpoint"
headers = {
"Authorization": "Bearer my_access_token",
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
In the example above, we're setting two custom headers: Authorization
and Content-Type
. These headers will be included in the HTTP request sent to the https://api.example.com/endpoint
URL.
If you need to update or add a header to an existing request, you can use the update()
method on the headers
dictionary:
headers = {
"Authorization": "Bearer my_access_token",
"Content-Type": "application/json"
}
## Update an existing header
headers.update({"Content-Type": "application/xml"})
## Add a new header
headers.update({"X-Custom-Header": "my_value"})
This approach allows you to easily modify the headers without having to recreate the entire dictionary.
Alternatively, you can use the set_header()
method on the requests.Request
or requests.PreparedRequest
objects to set custom headers:
from requests import Request, Session
url = "https://api.example.com/endpoint"
headers = {
"Authorization": "Bearer my_access_token",
"Content-Type": "application/json"
}
req = Request('GET', url, headers=headers)
prepared = req.prepare()
prepared.headers.update({"X-Custom-Header": "my_value"})
session = Session()
response = session.send(prepared)
In this example, we first create a Request
object with the initial headers, then use the prepare()
method to create a PreparedRequest
object. We can then update the headers on the PreparedRequest
object before sending the request using a Session
object.
By understanding how to set custom headers in Python Requests, you can enhance your web applications and API integrations, ensuring that the necessary metadata is included in your HTTP requests.