← Back to libraryQuestion 207 of 468
🐍PythonIntermediate

API Testing with the requests Library

📌 Definition:

requests is Python's de facto HTTP client for API testing. It makes GET/POST/PUT/DELETE calls and exposes status_code, headers, and .json() for assertions.

📖 Detailed Explanation:

r = requests.get(url, params={...}, headers={...}) returns a Response; check r.status_code, parse the body with r.json(), and read r.headers. POST JSON with requests.post(url, json=payload) (sets Content-Type automatically). Sessions (requests.Session()) persist cookies/auth across calls. Testers assert on status codes, response schema/fields, and headers, and use requests for fast setup (creating data via the API before a UI test). Add timeout= to avoid hanging tests, and raise_for_status() to fail fast on 4xx/5xx.

🔑 Key Points:
  • requests.get/post/put/delete; json= sends JSON bodies
  • Response: .status_code, .json(), .headers
  • Session() persists cookies/auth across requests
  • Always set timeout=; use raise_for_status() to fail fast
🌍 Real-World Example:

def test_create_user(): r = requests.post(f'{API}/users', json={'name': 'QA'}); assert r.status_code == 201; assert r.json()['name'] == 'QA' — validating the create endpoint's status and body.

🎯 Scenario-Based Interview Question:

An API test occasionally hangs forever in CI. What's the likely cause and the one-line safeguard?