Python Requests Example with Headers
If you're looking to make HTTP requests in Python, the requests
library is a great choice. It's simple to use and doesn't require any external dependencies.
What are Headers?
Headers are pieces of information that can be sent along with an HTTP request or response. They provide additional information about the request or response, such as the content type or the user agent.
How to Use Headers with Requests
To include headers in your requests with Python's requests
library, you can simply pass a dictionary containing the headers to the headers
parameter of the request functions. Here's an example:
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Content-Type': 'application/json'
}
response = requests.get('https://www.example.com', headers=headers)
In this example, we're sending two headers with our request: the user agent and the content type. We're using a dictionary to define these headers and passing it to the headers
parameter of the get
function.
Multiple Ways to Define Headers with Requests
There are multiple ways to define headers when making requests with Python's requests
library. Here are a few examples:
- Passing headers as a dictionary, as shown in the example above
- Using the
headers
parameter with a string of headers in the format'Header-Name: header-value'
- Using the
headers
parameter with a list of tuples, where each tuple contains a header name and value
Here's an example of using the headers
parameter with a string of headers:
import requests
headers = 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36\r\nContent-Type: application/json'
response = requests.get('https://www.example.com', headers=headers)
In this example, we're using a string to define our headers, separating each header with a newline character and a carriage return. This is equivalent to passing a dictionary of headers.
Here's an example of using the headers
parameter with a list of tuples:
import requests
headers = [
('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'),
('Content-Type', 'application/json')
]
response = requests.get('https://www.example.com', headers=headers)
In this example, we're using a list of tuples to define our headers, where each tuple contains a header name and value.