Testing REST APIs with the requests Library
Basic API check
Section titled “Basic API check”import requests
def test_status_and_json_shape():
r = requests.get("https://httpbin.org/json", timeout=10)
assert r.status_code == 200
data = r.json()
assert "slideshow" in data
assert "title" in data["slideshow"]Use sessions for many calls
Section titled “Use sessions for many calls”import requests
def test_many_calls():
with requests.Session() as s:
s.headers.update({"User-Agent": "qa-suite/1.0"})
r = s.get("https://httpbin.org/get", timeout=10)
assert r.status_code == 200- Always set timeouts
- Prefer stable environments (staging)
- Validate both happy path and error responses
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Write a unittest TestCase
Section titled “Exercise 1 – Write a unittest TestCase”Exercise 2 – assertRaises
Section titled “Exercise 2 – assertRaises”Exercise 3 – setUp and tearDown
Section titled “Exercise 3 – setUp and tearDown”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading