Recreate It in Code: requests + pytest with Shared State
Postman is great for poking around by hand. But an interviewer wants a suite that runs itself, the same way, every time. Good news — the same CRUD flow moves to Python almost one-to-one.
The idea, in one line
The requests library sends the HTTP calls, and pytest runs your checks and tells you when one fails. Together they turn your Postman clicks into version-controlled code.
The moves you'll use
- Each verb is a function:
requests.get,requests.post(url, json=payload),requests.put,requests.delete - Read the reply with
r.status_codeandr.json() - Send a query string with
params=and headers withheaders= - Always add
timeout=so a hung server can't freeze your whole suite
See it work
Real APIs are stateful: you create a record, then read, update and delete that same id. A requests.Session() keeps shared settings (like default headers) across calls, and a pytest fixture — reusable setup — hands that session to each test.
import requests, pytest
BASE = "https://jsonplaceholder.typicode.com"
@pytest.fixture
def session():
s = requests.Session()
s.headers.update({"Accept": "application/json"})
return s # reused across the calls in one test
def test_create_then_read(session):
# CREATE
r = session.post(f"{BASE}/posts",
json={"title": "qa", "userId": 1}, timeout=5)
assert r.status_code == 201
new_id = r.json()["id"] # carry this id forward
# READ the same resource
r = session.get(f"{BASE}/posts/{new_id}", timeout=5)
assert r.status_code == 200Read it top to bottom: you created a record, grabbed the id it gave back, then used that id to read the record again. That create-then-reuse chain is the backbone of the whole suite.
Advanced — how pytest finds and reports
pytest auto-discovers any file named test_*.py and any function named test_, then runs your assert lines. When an assert fails, it prints both sides of the comparison — so a wrong status code reads like a ready-made bug report instead of a cryptic error.
Grounded in the official Requests quickstart and pytest docs
All lessons in API Automation from Zero to Confident
- The HTTP Mental Model & Your First Postman Collection
- Recreate It in Code: requests + pytest with Shared State
- Trust the Shape: Schema Validation & Negative Testing
- Getting Past the Gate: API Keys, Bearer/JWT & OAuth2
- SQL for Testers: Prove the API Actually Wrote to the DB
- Mocking & Contracts: Fast, Offline, Reliable Tests