9
What library should I use for making HTTP requests in Python and how do I use it?
Loading...
Q&A · Answered
What library should I use for making HTTP requests in Python and how do I use it?
Accepted answer
import requests
# GET request
response = requests.get('https://api.example.com/data')
data = response.json()
# POST request with data
response = requests.post('https://api.example.com/submit',
json={'name': 'John', 'email': 'john@example.com'},
headers={'Authorization': 'Bearer token'}
)
# Handle errors
response.raise_for_status() # Raises exception for 4xx/5xx
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.RequestException as e:
print(f"Request failed: {e}")Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.