Writing AI Prompts That Produce Testable API Assertions
I've watched plenty of people paste a one-line request into GitHub Copilot Chat or a coding agent, get back a test file, and then spend longer untangling it than it would have taken to write it. The tool is rarely the problem. The prompt is. Vague input gives vague output, and in API testing vague output means assertions that check the wrong thing, skip the error paths, or pass for the wrong reason.
Writing a good prompt for test generation is the same skill as writing a good test. You need to know what you're asserting, why it matters, and what shape the data takes before you ask for code. Bring that clarity and the output becomes something you edit rather than rewrite.
This matters more as agents take on whole tasks instead of single completions. An agent working in your repository will write a dozen tests from one instruction, so the quality of that instruction, and of the standing rules in your repo, decides what lands in your suite. Here's how I structure those prompts, how I move the repeatable parts into an instruction file, and what I never accept no matter how good the prompt was.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
Give the model the schema, the status and the business rule
"Write a pytest test for the orders API" tells the model almost nothing. It doesn't know the response shape, the expected status code, or what rule the test protects. You'll get a skeleton that runs and asserts very little. A prompt that works looks more like this:
Write a pytest test for POST /orders.
Request body: {"product_id": 42, "quantity": 2}
On success the API returns HTTP 201 with JSON containing:
- "order_id": a non-empty string
- "status": exactly "pending"
- "total_price": a number greater than 0
Also test: quantity 0 returns HTTP 400 with an "error" field.
Use the requests library and the existing api_base_url fixture. No mocking.
That gives the model three things: the schema, the status code and the business rule. The business rule is the part people skip, and it matters most. assert data["status"] is not None protects almost nothing. assert data["status"] == "pending" documents intent and catches a real regression. If you don't know the rule, that's a sign to go and find out before anyone writes the test, human or agent.
Notice I wrote "a number", not "a float". JSON doesn't distinguish, and Python's json module turns 10 into an int and 10.5 into a float. If you prompt for a float, you'll often get isinstance(x, float), which fails on a perfectly valid whole-number price. Precise prompts include precise types.
Asking for one error path in the same prompt pays off too. It pushes the model to think about branches instead of only the happy path, and the file it hands back is closer to complete.
Tell it which framework conventions you already use
Once you're working inside a real suite, the prompt has to carry your conventions. For pytest I name the fixtures and the assertion style:
Use the fixture api_client (a requests.Session; call it with full URLs
built from the api_base_url fixture).
Test GET /users/{id}: returns 200, "email" contains "@", and "role" is
one of ["admin", "editor", "viewer"].
Use plain assert statements, not unittest-style self.assert* methods.
A plain requests.Session has no base URL setting, so I say explicitly how URLs are built. Without that, models sometimes invent a base_url attribute that doesn't exist. Being precise about your own fixtures is the cheapest fix there is.
For Behave, say whether you want the feature file, the steps or both, and how setup works:
Write step definitions for this scenario:
Given a valid auth token
When I send GET /products?category=electronics
Then the response status is 200
And each item in "products" has a non-null "sku" and a "price" greater than 0
context.base_url and context.session are set in environment.py; do not set them up again.
Reuse existing steps from features/steps/common_steps.py where the wording matches.
That last line stops the model from inventing a parallel setup pattern or duplicating steps you already have. I go further into this in prompting an AI assistant to write Behave step definitions.
I end most prompts with a constraints block: no unittest.mock, no hardcoded base URL, no new dependencies. Negative constraints stop the model filling gaps with patterns you'll have to strip out.
Move the repeated parts into an instruction file
If you type the same constraints every time, they belong in the repository, not in your head. Copilot reads repository-wide guidance from .github/copilot-instructions.md, and most coding agents support a similar instructions file. That's where conventions go so every prompt, and every agent task, starts from them:
## API test rules
- Assert on documented behaviour: status code, required fields, types, business values.
- Never assert on whatever the current response happens to contain unless the spec says so.
- Every new endpoint test includes at least one error path.
- No hardcoded tokens or URLs; use the fixtures in tests/conftest.py.
- No response-time assertions in functional tests.
- Never wrap a request and its assertions in try/except.
Once that's in place, your per-task prompt can shrink to the parts that are actually specific: the endpoint, the schema and the rule. The agent brings the rest.
The rule about "whatever the current response happens to contain" is the one I care most about. An agent that can call the API will happily run it, copy the response into assertions and call it a test. That snapshot passes today and protects nothing, because it encodes current behaviour rather than intended behaviour.
Edit, re-prompt or reject
My rule of thumb: if the structure is right but the assertions are weak, edit. If the structure is wrong, with the wrong fixture pattern, wrong framework conventions or invented imports, re-prompt with more constraints. Editing a structurally wrong test means fighting the model's assumptions line by line.
When I re-prompt, I respond to the draft directly: "This asserts the status but not the pagination envelope. The response has a top-level meta object with total_count (int), page (int) and has_next (bool). Add assertions for all three, plus a case where has_next is false." Specific feedback gets specific fixes.
Some things I reject on sight, regardless of the prompt:
- Hardcoded credentials. A placeholder token has a way of getting committed. Replace it with an environment variable or fixture immediately.
- Response-time assertions like
response.elapsed.total_seconds() < 2.0in functional tests. They're flaky in shared CI runners and belong in performance testing. - Try/except blocks that swallow failures. A test that catches the assertion error and prints a message always passes. It isn't a test.
- Assertions that can't fail.
assert response.json()orassert "id" in data or True. I make a habit of breaking the API response in my head and asking whether this test would notice.
That last check is the quickest review habit I know. For every generated assertion, ask what change in the API would make it fail. If the answer is "nothing realistic", it's decoration. There's more on that review process in reviewing AI-suggested test coverage before you commit it.
The prompt is where your knowledge goes in
AI tools are good at assertion boilerplate and test scaffolding. They don't know your business rules, your conventions or the edge cases that have hurt you before. The prompt and the instruction file are where you put that knowledge in. The more specific you are, the less cleanup you do, and the more the output looks like something a careful engineer on your team would write. If you want to practise this end to end with Behave or Cucumber, VS Code and GitHub Copilot, that's what my API testing courses are built around.