API TESTING

Testing API Responses That Vary by Query Parameter Combo

Query parameters look harmless. You add ?status=active to a URL and move on. But once an endpoint accepts three or four parameters, each with several meaningful values, you're in a combinatorial space that grows fast and breaks in ways single-parameter tests never catch. The bugs live in the interactions: what the API does when sort=desc meets page=1 and status=archived, a question nobody thought to ask while writing one test at a time.

Coding agents change both sides of this. An assistant like Copilot or Claude Code is very good at the tedious part, listing combinations and writing parametrised cases. It's much less reliable at the part that matters, deciding what the correct response is for each one, and it tends to fill that gap by copying whatever the endpoint currently returns. Meanwhile, LLM agents that call your search or filter endpoints as tools will send combinations no human client ever did, including contradictory ones.

In this article I'll walk through how I map the parameter space, choose which combinations to test, structure them in pytest without drowning in cases, write checks that hold for any combination, and divide the work so an agent widens coverage without inventing the expected results.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Map the parameter space first

Before touching code, I build a small grid from the docs or the source. List every query parameter, then the equivalence classes for each: not every possible string, just the values that should behave differently. For a list endpoint:

  • status: active, archived, all, omitted
  • sort: asc, desc, omitted
  • page: first, middle, last, beyond the last
  • q: matching term, non-matching term, empty string, omitted

The full product of even this modest grid is close to two hundred combinations. You don't need all of them. A pairwise set, where every pair of values appears together in at least one case, catches most two-parameter interaction bugs with far fewer cases. Libraries such as allpairspy can generate the set for you:

from allpairspy import AllPairs

PARAMETERS = [
    ["active", "archived", "all", None],   # status
    ["asc", "desc", None],                 # sort
    [1, 2, 9999],                          # page
    ["widget", "zzz-no-match", "", None],  # q
]

PAIRWISE_CASES = [
    {k: v for k, v in zip(("status", "sort", "page", "q"), combo) if v is not None}
    for combo in AllPairs(PARAMETERS)
]

None stands for "parameter omitted," and the dict comprehension drops it, so requests leaves it out of the query string. The grid also forces the more important question: what should the response be for each combination? If you can't answer that for status=archived&q=, you don't understand the contract yet, and that's a conversation to have before writing tests. Page boundaries add their own edge cases; testing paginated API responses without missing edge cases goes deeper.

Invariants: checks that work for any combination

A generated list of cases is only useful if each case can be judged. Rather than a hand-written expected result for every combination, I lean on invariants, properties that must hold whatever the parameters are:

import pytest
import requests

ITEMS_URL = "https://api.example.test/items"


def check_invariants(params: dict, body: dict) -> None:
    items = body["items"]
    status = params.get("status", "active")  # documented default
    if status != "all":
        assert all(i["status"] == status for i in items), "status filter leaked other items"
    if params.get("q"):
        assert all(params["q"].lower() in i["name"].lower() for i in items), "q filter ignored"
    sort = params.get("sort", "asc")
    names = [i["name"] for i in items]
    assert names == sorted(names, reverse=(sort == "desc")), f"not sorted {sort}"


@pytest.mark.parametrize("params", PAIRWISE_CASES, ids=str)
def test_item_filters_hold_for_combination(params):
    response = requests.get(ITEMS_URL, params=params, timeout=10)
    assert response.status_code == 200, f"{params}: HTTP {response.status_code}"
    check_invariants(params, response.json())

The invariants encode the contract once: filters really filter, sort really sorts, defaults are what the docs say. Adjust them to your API, for example if sorting is by date rather than name or search also matches descriptions. Then every combination, generated or hand-picked, gets a meaningful check. An empty result passes the invariants, so pair them with a seeded dataset where you know certain combinations must return items.

Hand-picked cases with specific expectations

Some combinations deserve explicit expected results, written by a person. Give each an ID so failures are readable:

EXPLICIT_CASES = [
    pytest.param({"status": "active", "page": 9999}, 200, 0, id="beyond-last-page-empty"),
    pytest.param({"status": "archived", "q": "widget"}, 200, 2, id="archived-widget-seeded"),
    pytest.param({"status": "bogus"}, 400, None, id="invalid-status-rejected"),
]


@pytest.mark.parametrize("params, status_code, count", EXPLICIT_CASES)
def test_item_filter_explicit(params, status_code, count, seeded_items):
    response = requests.get(ITEMS_URL, params=params, timeout=10)
    assert response.status_code == status_code
    if count is not None:
        assert len(response.json()["items"]) == count

The expected count of 2 only makes sense because seeded_items creates a known dataset. Expected values should come from data you control, never from a previous run. In Behave the same cases fit a Scenario Outline with an Examples table, which reads well for non-engineers as long as the expectations stay simple.

Combinations that break more often than you'd expect

  • Conflicting filters. status=active&include_deleted=true forces the API to choose. Does one win, does it error, does it return nothing? It's often undocumented, and developers disagree about the answer. Decide, then test.
  • Omitted versus explicit default. Leaving a parameter out should match passing its documented default. Test both and assert identical responses; a difference is an inconsistency clients will trip over.
  • Boundaries in combination. limit=0 may be fine alone and take a different code path with a sort applied. An empty q plus a restrictive filter is a classic source of unexpected 500s.
  • Repeated parameters. ?status=active&status=archived is valid in a URL. Does the API take the first, the last, both, or fail? Pass a list of tuples to requests to send it.
  • Order sensitivity. Rare, but a hand-rolled parser can treat ?a=1&b=2 differently from ?b=2&a=1. One reversed-order variant of your most critical combination is cheap insurance.

Splitting the work with a coding agent

This is a good task to share with an agent, as long as the split is explicit. The agent can read the endpoint's code or OpenAPI spec and propose equivalence classes you missed, generate the pairwise list, and write the parametrised tests. A person owns the invariants and every explicit expected value. I write that rule into the repository instructions (.github/copilot-instructions.md for Copilot, or your agent's equivalent):

## Filter and search endpoint tests
- Generate combinations in PAIRWISE_CASES; every case runs through check_invariants().
- Never set an expected count or body from a live response. If a case needs a specific
  expectation, add it to EXPLICIT_CASES with a TODO for a human to confirm.
- If a combination returns 500, keep the test failing and report it; do not remove the case.

That last rule matters. An agent iterating until the suite is green will otherwise "fix" a 500 by dropping the combination that caused it, which deletes exactly the bug you were looking for.

The same thinking applies if your API is a tool for an LLM agent. Models produce parameter combinations based on the user's wording, so contradictory or unusual combinations are normal traffic, not edge cases. The invariant tests above protect those callers too, and a clear 400 for a nonsensical combination gives the agent something to correct, where a silently empty list gives it a wrong answer.

Running it sustainably

Keep the explicit cases and a small pairwise set on every pull request for critical filter endpoints, and move the wider generated matrix to a nightly run. Tags make that split easy; tagging API tests so CI can run the right subset shows how I set it up, and structuring pytest parametrize for API edge cases covers keeping case tables readable. If you'd like to build this kind of coverage hands-on, with GitHub Copilot drafting and you reviewing, my API testing courses walk through it.