QA AND TEST AUTOMATION · PART 4 · API TESTING · PYTHON · 42 OF 112

API Testing with Python: pytest and httpx

An API test suite in Python with pytest and httpx (requests works the same way): a client fixture with the base URL from an environment variable, a reset fixture, a logged-in user fixture, parametrized boundary tests, plain assert messages, markers and parallel runs. Run for real against ShopRung: 6 passed, and the quantity-limit bug caught with a clear failure.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Session client fixture
  • reset and login fixtures
  • plain asserts
  • parametrize
  • markers, xdist, JUnit XML

Notes

Setup

Install pytest and httpx. Httpx has a client with a base address and works much like the popular requests library, which is also fine; the ideas in this episode are the same. The layout is simple: a conftest file for shared fixtures, test files named test underscore something, a pytest ini file for settings and markers, and a requirements file with pinned versions, so CI installs exactly what you used.

Install and layout
pip install pytest httpx

shoprung-api-tests/
  conftest.py    # fixtures
  test_cart.py
  test_orders.py
  pytest.ini     # markers
  requirements.txt

requests works too: same ideas

Client fixture

A fixture is a function that prepares something for a test. The client fixture creates one httpx client for the whole session, with the base URL read from an environment variable, and localhost as the default, plus a ten second timeout so a hung server cannot hang CI. Yield hands the client to the tests, and the with block closes it at the end. Run against staging by setting base URL, no code changes.

conftest.py
import os, httpx, pytest

BASE = os.getenv("BASE_URL",
                 "http://localhost:8080")

@pytest.fixture(scope="session")
def client():
    with httpx.Client(base_url=BASE,
                      timeout=10) as c:
        yield c

Data fixtures

Two more fixtures. Reset has auto use set to true, so it runs before every test and puts ShopRung's data back to the start, which keeps tests independent. The alice fixture logs in through the API and adds the bearer token to the client's headers. A test that needs a logged in customer just asks for alice as a parameter. After the test, the fixture removes the header again, so the next test starts logged out.

More fixtures
@pytest.fixture(autouse=True)
def reset(client):
    client.post("/api/test/reset")

@pytest.fixture
def alice(client):
    r = client.post("/api/auth/login",
        json={"email": ALICE, ...})
    assert r.status_code == 200
    client.headers["Authorization"] =
        f"Bearer {r.json()['token']}"

A test

Here is the save ten test again, now in Python. The test asks for alice, adds four notebooks, exactly fifty dollars, applies save ten, and checks with plain assert statements: status two hundred, discount five hundred cents, total forty nine ninety nine. Pytest rewrites asserts, so when one fails it prints both sides of the comparison. No matcher library to learn.

test_cart.py
def test_save10_at_exactly_50(alice):
    alice.post("/api/cart/items",
      json={"productId": 1,
            "quantity": 4})
    r = alice.post("/api/cart/coupon",
      json={"code": "save10"})
    assert r.status_code == 200
    cart = r.json()
    assert cart["discountCents"] == 500
    assert cart["total"] == "$49.99"

Parametrize

Parametrize turns one function into many tests. The quantity rule gets four cases: zero gives four hundred, one and ten give two hundred, eleven gives four hundred. Pytest reports each case separately, with the values in its name, like test quantity limits eleven dash four hundred. The message after the comma prints the response body when the assert fails, which saves a debugging round trip.

Boundary values
@pytest.mark.parametrize(
  "qty, status",
  [(0, 400), (1, 200),
   (10, 200), (11, 400)])
def test_quantity_limits(alice,
                        qty, status):
    r = alice.post("/api/cart/items",
      json={"productId": 1,
            "quantity": qty})
    assert r.status_code == status,
        r.text

A real run

We ran this suite against ShopRung. Six tests, all passed, in under a second. Then we switched on the quantity limit bug, which lets you add eleven of an item. Exactly one test failed: quantity limits, eleven, four hundred, with assert two hundred equals four hundred, and the response body. The name alone tells you which rule broke and with which value. That is what a good failure looks like.

pytest -q
BASE_URL=http://localhost:8080
  pytest -q
......                 [100%]
6 passed in 0.80s

bug "quantity-limit" on:
FAILED test_quantity_limits
  [11-400]
  assert 200 == 400
1 failed, 5 passed

Organising

As the suite grows, organise it. Markers tag tests, like smoke, and dash m smoke runs only those. Dash k selects by name, dash x stops at the first failure, and last failed reruns only what failed. The x dist plugin runs tests in parallel with dash n auto, but only if tests do not share data, so a global reset must become per user data first. Junit XML writes a report CI tools understand.

Useful pytest options
@pytest.mark.smoke
pytest -m smoke
pytest -k coupon
pytest -x          # stop at 1st
pytest --lf       # last failed
pytest -n auto    # pytest-xdist
pytest --junitxml=results.xml

pytest.ini: markers =
  smoke: fast checks

Models

Python dictionaries are quick, but a typo in a key only fails at run time. For bigger suites, a pydantic model gives typed responses: a cart model with integer fields for subtotal, discount and total. Model validate checks the JSON matches, with a clear error if a field is missing or has the wrong type, and the editor completes field names. It is the Python cousin of the Java records from the last episode.

Typed responses
from pydantic import BaseModel

class Cart(BaseModel):
    subtotalCents: int
    discountCents: int
    totalCents: int

cart = Cart.model_validate(r.json())
assert cart.totalCents == 4999
# wrong type → clear error

Common mistakes

Habits to avoid. HTTP calls without a timeout, which can hang a pipeline forever. The base URL repeated in every test. Tests that only pass in a certain order. Login code at module level instead of in a fixture. Checking only that the response is okay. Try and except blocks that swallow assertion errors. Unpinned requirements. And parallel runs on shared data, which creates flaky failures.

Avoid these
  • requests.get without timeout
  • base URL in every test
  • tests that depend on order
  • module-level login code
  • a bare assert r.ok only
  • try/except that hides fails
  • unpinned requirements
  • parallel runs on shared data

Say it like this

In the interview: I use pytest with httpx or requests. Conftest holds a session client with the base URL from the environment and a timeout, a data fixture that resets or creates test data, and login fixtures per role. Parametrize covers boundaries, plain asserts include the response body as the message, markers select smoke tests, x dist runs in parallel when data is isolated, and junit XML feeds CI.

In the interview
  • "pytest with httpx or requests.
  • conftest holds a session client
  • (base URL from env, timeouts), a reset or data fixture, and login fixtures per role.
  • parametrize covers boundaries;
  • plain asserts with the body as message. Markers for smoke, xdist for speed, JUnit XML
  • for CI."

Interview questions

Q1What is a pytest fixture?

A function decorated with @pytest.fixture that provides setup (and teardown after yield) to tests that name it as a parameter; scope controls how often it runs.

Q2What are fixture scopes?

function (default, every test), class, module, package and session; a session-scoped HTTP client is created once for the whole run.

Q3What does autouse=True do?

Applies the fixture to every test in its scope without the test naming it, useful for resets or logging.

Q4How do you write data-driven tests in pytest?

With @pytest.mark.parametrize, listing argument names and value tuples; each tuple becomes a separately reported test.

Q5Where do shared fixtures live?

In conftest.py; pytest discovers it automatically for tests in that directory and below.

Q6How do you run pytest tests in parallel?

With the pytest-xdist plugin (pytest -n auto), provided tests do not share or reset the same data.

Q7requests or httpx?

Both work well for API tests. httpx adds a base_url client, HTTP/2 and async support with a requests-like API.

Q8How do you point a pytest suite at different environments?

Read the base URL from an environment variable or a command-line option in conftest.py, with a sensible local default.