Structuring Pytest Parametrize for API Edge Cases
pytest.mark.parametrize is the best tool I know for API edge cases. One test function, a table of inputs and expected outcomes, and pytest turns it into a separate test for each row. Twenty validation cases that would have been twenty copy-pasted functions become one readable test.
It's also easy to turn into a mess. Parameter lists grow to dozens of anonymous tuples, test ids become test_create_user[payload7-400], a failure tells you nothing about which edge case broke, and nobody can tell which rows are still meaningful. Structure is what keeps parametrize useful as the table grows.
That growth happens faster now. Ask GitHub Copilot or a coding agent for edge cases and it will produce a long list in seconds, some of them valuable, some duplicates, some with expected results it guessed. In this article I'll cover how I structure parametrised API tests so they stay readable and debuggable, and how I review the case tables that an assistant generates.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Start with readable ids
The default ids pytest generates for dicts and objects are positional, like payload0 and payload1. When one fails in CI, you have to count rows to find out which case it was. Give every case a name with pytest.param(..., id=...):
import pytest
@pytest.mark.parametrize("payload, expected_status", [
pytest.param({"email": "", "name": "QA"}, 422, id="empty-email"),
pytest.param({"email": "not-an-email", "name": "QA"}, 422, id="malformed-email"),
pytest.param({"name": "QA"}, 422, id="missing-email"),
pytest.param({"email": "qa@example.test", "name": ""}, 422, id="empty-name"),
pytest.param({"email": "qa@example.test", "name": "x" * 256}, 422, id="name-too-long"),
])
def test_create_user_rejects_invalid_input(api, payload, expected_status):
response = api.post("/users", json=payload)
assert response.status_code == expected_status, response.text
Now a failure reads test_create_user_rejects_invalid_input[name-too-long], and you can run that one case with pytest -k name-too-long. Ids are the cheapest documentation you'll ever write. Check whether your API returns 400 or 422 for validation errors and use what it documents; frameworks differ.
Split by outcome, not by endpoint
A common mistake is one giant parametrised test per endpoint that mixes success cases, validation errors and permission errors, with branching inside the test to decide what to assert. Once a test body contains if expected_status == 201:, it's really several tests sharing a function.
I split by outcome instead: one parametrised test for inputs that should be accepted, one for inputs that should be rejected with a validation error, one for permission cases. Each test has a single, simple assertion path. The rejected-input test can also check the error body, for example that the response names the offending field:
@pytest.mark.parametrize("payload, bad_field", [
pytest.param({"email": "not-an-email", "name": "QA"}, "email", id="malformed-email"),
pytest.param({"email": "qa@example.test", "name": ""}, "name", id="empty-name"),
])
def test_validation_error_names_the_field(api, payload, bad_field):
response = api.post("/users", json=payload)
assert response.status_code == 422
fields = [error["field"] for error in response.json()["errors"]]
assert bad_field in fields
The shape of the error body here is an example; assert against your own API's documented error format. For the wider topic, see testing API error responses beyond the happy path.
Use marks for known issues, not deleted rows
When an edge case exposes a known bug, the tempting move is to delete or comment out the row. Then the case is forgotten. Mark it instead:
pytest.param(
{"email": "QA@Example.Test", "name": "QA"}, 409,
id="duplicate-email-different-case",
marks=pytest.mark.xfail(reason="BUG-123: email uniqueness is case-sensitive", strict=True),
),
With strict=True, the test fails if the case unexpectedly passes, which tells you the bug was fixed and the mark should come off. The case stays visible in every report until then.
Move large tables out of the test
Past fifteen or twenty rows, an inline list starts to bury the test logic. Move the cases into a module of their own as plain data, and keep the test short:
# tests/cases/user_validation.py
import pytest
INVALID_USERS = [
pytest.param({"email": "", "name": "QA"}, "email", id="empty-email"),
pytest.param({"email": "not-an-email", "name": "QA"}, "email", id="malformed-email"),
# ...
]
# tests/api/test_users.py
import pytest
from tests.cases.user_validation import INVALID_USERS
@pytest.mark.parametrize("payload, bad_field", INVALID_USERS)
def test_validation_error_names_the_field(api, payload, bad_field):
...
A data module is easier to review than a test function, and it's the natural place to add cases. Be careful with stacked parametrize decorators. Two stacked decorators produce every combination of their values, which is occasionally what you want and often an accidental explosion in test count. When cases interact, I list the specific combinations explicitly. For query parameters in particular, see API responses that vary by query parameter combination.
Reviewing edge cases an assistant generates
Edge-case tables are one of the things AI assistants are genuinely good at suggesting. Ask for invalid inputs for a user-creation endpoint and you'll get empty strings, unicode, very long values, wrong types, nulls and injection-style strings, often more than you'd have thought of. The problems are in the expected results and in volume.
My review checklist for a generated case table:
- Where did each expected status come from? An agent that ran the tests against your API may have filled in whatever the API returned. If the API wrongly returns 500 for a null name, the table now asserts 500. Check expected values against the documentation, not the current behaviour.
- Does every case have a meaningful id? If the agent couldn't name it, it may not know what it's testing.
- Are rows distinct? Five spellings of "invalid email" exercise the same validation branch. Keep one or two.
- Is anything missing? Generated tables tend to be heavy on input validation and light on boundaries that matter to the business, such as maximum quantities, currency precision and state conflicts.
I write these expectations into the repository instructions the agent reads, .github/copilot-instructions.md for Copilot or your agent's equivalent: every case needs a pytest.param id, expected values must come from the API documentation, and known bugs get xfail with a ticket rather than an expected value that matches the bug.
The same structure works when you test features that call a language model. A table of named cases, each with an input and a check, is how an evaluation set is usually organised. The difference is that each case runs several times and you assert a pass rate, because the output varies between runs. Readable ids matter even more there, because "which cases got worse?" is the question you'll ask after every prompt or model change.
Tables that stay readable
Parametrize scales well when each case has a name, each test has one outcome, known bugs are marked rather than deleted, and large tables live in their own data module. Generated cases are welcome, as long as a person checks where every expected value came from. If you want to practise building API suites this way with Python, VS Code and GitHub Copilot, my API testing courses walk through it.