Python Requests Library: Core Modules, Methods, Parameters, and Usage Examples
This tutorial explains the Python requests library, covering its core modules, HTTP methods (GET, POST, PUT, DELETE), key parameters, session management, and exception handling with practical code examples for API interaction and best practices.
The requests library consists of core modules: requests for sending HTTP requests, requests.Session for managing sessions, requests.Response for handling responses, and requests.exceptions for handling exceptions.
It provides methods for various HTTP requests: .get(), .post(), .put(), .delete(), .head(), .options().
Key parameters include url, params, data, json, headers, cookies, auth, and timeout.
Example of a GET request:
import requests
url = "https://api.example.com/users"
params = {"page": 1, "limit": 10}
response = requests.get(url, params=params)
print(response.status_code)
print(response.json())Example of a POST request:
import requests
url = "https://api.example.com/users"
headers = {"Content-Type": "application/json"}
data = {"username": "testuser", "password": "testpass"}
response = requests.post(url, json=data, headers=headers)
print(response.status_code)
print(response.json())Example of a PUT request:
import requests
url = "https://api.example.com/users/123"
headers = {"Content-Type": "application/json"}
data = {"username": "testuser", "email": "[email protected]"}
response = requests.put(url, json=data, headers=headers)
print(response.status_code)
print(response.json())Example of a DELETE request:
import requests
url = "https://api.example.com/users/123"
response = requests.delete(url)
print(response.status_code)
print(response.json())Using Session to persist parameters across requests:
import requests
session = requests.Session()
session.headers.update({"Content-Type": "application/json"})
response1 = session.get("https://api.example.com/users")
response2 = session.post("https://api.example.com/users", json={"username": "testuser"})
print(response1.status_code)
print(response2.status_code)Exception handling for requests:
import requests
from requests.exceptions import HTTPError, Timeout, RequestException
try:
response = requests.get("https://api.example.com/users", timeout=5)
response.raise_for_status()
except HTTPError as http_err:
print(f"HTTP error: {http_err}")
except Timeout:
print("Request timeout")
except RequestException as err:
print(f"Request error: {err}")
else:
print("Request successful")
print(response.json())In summary, requests is a powerful HTTP client library suitable for API automation testing. Mastering its components and invocation methods enables easy sending of various HTTP requests and handling of response data.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.