Testing REST APIs with the requests Library
Basic API check
api_test_requests.py
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"]api_test_requests.py
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
api_session.py
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 == 200api_session.py
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 == 200Tips
- Always set timeouts
- Prefer stable environments (staging)
- Validate both happy path and error responses
๐งช Try It Yourself
Exercise 1 โ Write a unittest TestCase
Exercise 2 โ assertRaises
Exercise 3 โ setUp and tearDown
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
