Adding Headers
Include custom headers in requests:
import requests
headers = {
'User-Agent': 'MyApp/1.0',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
response = requests.get('https://api.example.com/data', headers=headers)
Basic Authentication
Use basic auth:
from requests.auth import HTTPBasicAuth
response = requests.get('https://api.example.com/data',
auth=HTTPBasicAuth('username', 'password'))
# Or simpler
response = requests.get('https://api.example.com/data',
auth=('username', 'password'))
Bearer Token Authentication
Use token-based auth:
headers = {
'Authorization': 'Bearer your-token-here'
}
response = requests.get('https://api.example.com/data', headers=headers)
API Key Authentication
Use API keys:
# In headers
headers = {'X-API-Key': 'your-api-key'}
response = requests.get('https://api.example.com/data', headers=headers)
# Or in query parameters
params = {'api_key': 'your-api-key'}
response = requests.get('https://api.example.com/data', params=params)
Using Sessions
Reuse connections and headers:
session = requests.Session()
session.headers.update({'Authorization': 'Bearer token'})
# All requests use the same headers
response1 = session.get('https://api.example.com/data1')
response2 = session.get('https://api.example.com/data2')
Best Practices
- Store credentials securely: Use environment variables
- Use sessions: For multiple requests to same API
- Set User-Agent: Identify your application
- Handle tokens: Refresh expired tokens
Next Steps
Learn about GET and POST requests for making API calls.