How to Set Headers in Python Requests: Simple Guide
To set headers in
python requests, pass a dictionary of headers to the headers parameter in the requests.get() or requests.post() function. For example, use requests.get(url, headers={'User-Agent': 'my-app'}) to send custom headers with your request.Syntax
Use the headers parameter in the requests methods to add custom HTTP headers. The value must be a dictionary where keys are header names and values are header values.
url: The web address you want to request.headers: A dictionary of header names and values.
python
import requests response = requests.get('https://example.com', headers={'User-Agent': 'my-app/1.0'})
Example
This example shows how to send a GET request with a custom User-Agent header and print the response status code and headers sent.
python
import requests url = 'https://httpbin.org/headers' headers = {'User-Agent': 'my-app/1.0', 'Accept': 'application/json'} response = requests.get(url, headers=headers) print('Status code:', response.status_code) print('Response JSON:', response.json())
Output
Status code: 200
Response JSON: {'headers': {'Accept': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'my-app/1.0', 'X-Amzn-Trace-Id': 'Root=1-...'}}
Common Pitfalls
Common mistakes when setting headers include:
- Not using a dictionary for
headers. - Using incorrect header names or casing (headers are case-insensitive but should be spelled correctly).
- Overwriting default headers unintentionally.
- Passing headers as a list or other data type instead of a dictionary.
Always pass headers as a dictionary and check the spelling of header names.
python
import requests # Wrong way: headers as a list (will cause error) # response = requests.get('https://example.com', headers=['User-Agent: my-app']) # Right way: response = requests.get('https://example.com', headers={'User-Agent': 'my-app'})
Quick Reference
Tips for setting headers in Python requests:
- Headers must be a dictionary:
{'Header-Name': 'value'}. - Use standard header names like
User-Agent,Accept,Authorization. - Headers are case-insensitive but use common casing for readability.
- Pass headers to
requests.get(),requests.post(), etc., via theheadersparameter.
Key Takeaways
Pass headers as a dictionary to the headers parameter in requests methods.
Use correct header names and values to avoid request errors.
Headers customize your HTTP request, like setting User-Agent or Authorization.
Avoid passing headers as lists or other incorrect types.
Check response to confirm headers were sent correctly.