Python Requests HTTP
Making HTTP requests in Python with the Requests library for APIs and web scraping.
GET Requests
import requests
# Simple GET request
response = requests.get('https://api.example.com/data')
# With query parameters
params = {'key': 'value', 'page': 1}
response = requests.get(url, params=params)
# Check status
response.status_code # 200 means success
response.ok # True if status < 400
response.json() # parse JSON response
POST Requests
# POST with JSON data
data = {'username': 'user', 'password': 'pass'}
response = requests.post(url, json=data) # automatically sets Content-Type
# POST with form data
response = requests.post(url, data=data)
# With headers (e.g., authentication)
headers = {'Authorization': 'Bearer token123'}
response = requests.post(url, headers=headers, json=data)
Response Handling
# Get response content
response.text # as string
response.json() # as JSON (dict/list)
response.content # as bytes
response.headers # response headers (dict)
# Error handling
try:
response.raise_for_status() # raises exception for 4xx/5xx
except requests.HTTPError as e:
print(f"Error: {e}")
except requests.Timeout:
print("Request timed out")