API Automation from Zero to Confident · Lesson 2 of 6

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.

By Shahriyar · Updated

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

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.

▸ try it
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 == 200

Read 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

  1. The HTTP Mental Model & Your First Postman Collection
  2. Recreate It in Code: requests + pytest with Shared State
  3. Trust the Shape: Schema Validation & Negative Testing
  4. Getting Past the Gate: API Keys, Bearer/JWT & OAuth2
  5. SQL for Testers: Prove the API Actually Wrote to the DB
  6. Mocking & Contracts: Fast, Offline, Reliable Tests