Generate an API Test Suite from OpenAPI Spec
Reads an OpenAPI 3.x specification and returns an API test suite that validates response schemas per documented status code, covers authentication, pagination, filtering, and the standard error responses (400, 401, 403, 404, 429, 500). Output is framework-agnostic plan plus Playwright APIRequestContext skeleton.
When to use it
- You have an OpenAPI spec and need to scaffold API tests fast.
- You're enforcing API contracts via tests instead of (or alongside) Pact contract testing.
- You want consistent rate-limit, auth, and pagination coverage across all endpoints.
- You're auditing API test coverage gaps against the actual spec.
The prompt
<role>You are an API testing specialist who has shipped suites for production REST APIs. You validate response schemas via $ref rather than redefining them, and you cover the standard error cases (400, 401, 403, 404, 429, 500) per endpoint instead of just happy paths.</role> <context>The team uses Playwright's APIRequestContext for API tests (also acceptable: supertest, axios + Jest, REST Assured). Tests run in CI against a deployed staging environment with seeded data. Schema validation uses Ajv with refs into the original spec.</context> <task>For the OpenAPI snippet I provide, generate:1. A test plan (Markdown table) listing test cases per endpoint × status code, grouped by happy path, auth, error responses, pagination/filtering, rate limiting.2. A Playwright APIRequestContext skeleton file demonstrating: schema validation via $ref, parameterized status code tests, auth header injection via fixture, pagination loop test.3. Identify gaps in the spec (missing 429 docs, ambiguous schemas, undocumented auth): list them separately.</task> <input>OpenAPI snippet (paths + components excerpt): {openapi}Auth scheme (Bearer, API key, OAuth): {auth}Framework preference: {framework}</input> <constraints>- Test plan covers EVERY documented status code per endpoint, not just 2xx.- Schema validation references components via $ref: never inline duplicate schemas. With Ajv, register the whole spec (`ajv.addSchema(spec, 'openapi.json')`) and get validators by pointer (`ajv.getSchema('openapi.json#/components/schemas/X')`) so nested refs resolve.- Auth header injection is a single fixture, not repeated per test.- Rate limit testing (429) is mandatory when documented; flagged as missing if not documented.- Pagination test exercises both first-page and middle-page (cursor or offset).</constraints> <output_format>Three sections:1. **Test plan**: Markdown table with columns: Endpoint, Method, Status, Test case, Priority.2. **Skeleton code**: Playwright APIRequestContext code block.3. **Spec gaps**: bullet list of missing or ambiguous spec content.</output_format> <approach>Before writing, scan the spec for what's documented vs missing.</approach>## RoleAPI testing specialist. Validates schemas via $ref. Covers standard errors (400/401/403/404/429/500), not just happy paths. ## ContextPlaywright APIRequestContext primary; supertest / axios+Jest acceptable. Staging env, seeded data. Ajv schema validation with refs. ## TaskFrom the OpenAPI snippet: produce (1) test plan table, (2) Playwright skeleton showing schema validation, auth fixture, pagination, parameterized status codes, (3) spec gaps list. ## Input- OpenAPI snippet: {openapi}- Auth: {auth}- Framework: {framework} ## Constraints- Cover EVERY documented status code per endpoint.- $ref for schemas; no inline duplication. Ajv: `addSchema(spec)` once, then `getSchema('openapi.json#/components/schemas/X')` so nested refs resolve.- Single auth fixture, not per-test.- 429 mandatory if documented; flagged if missing.- Pagination test covers first AND middle page. ## Output format3 sections: test plan table | skeleton code | spec gaps bullets. ## ApproachIdentify what's documented vs missing before writing.Example
Input
OpenAPI snippet (paths + components excerpt):
paths:
/users:
get:
summary: List users (paginated)
parameters:
- name: limit
in: query
schema: { type: integer, default: 20, maximum: 100 }
- name: cursor
in: query
schema: { type: string }
responses:
'200':
description: List of users
content:
application/json:
schema: { $ref: '#/components/schemas/UserPage' }
'401': { description: Unauthorized }
'429': { description: Rate limited, headers: { Retry-After: { schema: { type: integer } } } }
post:
summary: Create a user
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/CreateUserRequest' }
responses:
'201': { content: { application/json: { schema: { $ref: '#/components/schemas/User' } } } }
'400': { description: Validation error }
'401': { description: Unauthorized }
'409': { description: Email already exists }
Auth scheme: Bearer token (JWT)
Framework preference: Playwright APIRequestContextOutput
## Test plan
| Endpoint | Method | Status | Test case | Priority |
|----------|--------|--------|-----------|----------|
| /users | GET | 200 | List users with default limit; response matches UserPage schema | P1 |
| /users | GET | 200 | List users with limit=100 (max); schema match; result count <= 100 | P1 |
| /users | GET | 200 | Paginate via cursor; second page schema match; no overlap with first | P1 |
| /users | GET | 400 | limit=101 returns 400 (above max) | P2 |
| /users | GET | 401 | Request without Bearer returns 401 | P1 |
| /users | GET | 429 | Rapid requests trigger 429; Retry-After header present (integer) | P1 |
| /users | POST | 201 | Valid payload returns 201; response matches User schema | P1 |
| /users | POST | 400 | Missing required field returns 400 | P1 |
| /users | POST | 400 | Invalid email format returns 400 | P2 |
| /users | POST | 401 | Without Bearer returns 401 | P1 |
| /users | POST | 409 | Duplicate email returns 409 | P1 |
| /users | POST | 429 | (Spec gap): rate limit not documented for POST | P3 |
## Skeleton code
```typescript
import { test, expect, APIRequestContext } from '@playwright/test';
import Ajv from 'ajv';
import openapi from './openapi.json' with { type: 'json' };
// Register the whole spec once so nested $refs (#/components/...) resolve.
// strict: false lets Ajv skip OpenAPI-only keywords such as `example`.
const ajv = new Ajv({ allErrors: true, strict: false });
ajv.addSchema(openapi, 'openapi.json');
const validateUserPage = ajv.getSchema('openapi.json#/components/schemas/UserPage')!;
const validateUser = ajv.getSchema('openapi.json#/components/schemas/User')!;
const authedRequest = test.extend<{ api: APIRequestContext }>({
api: async ({ playwright }, use) => {
const token = process.env.TEST_BEARER!;
const api = await playwright.request.newContext({
baseURL: process.env.BASE_URL,
extraHTTPHeaders: { Authorization: `Bearer ${token}` },
});
await use(api);
await api.dispose();
},
});
authedRequest('GET /users returns paginated UserPage', async ({ api }) => {
const res = await api.get('/users?limit=20');
expect(res.status()).toBe(200);
const body = await res.json();
expect(validateUserPage(body), JSON.stringify(validateUserPage.errors)).toBe(true);
});
authedRequest('GET /users second page via cursor has no overlap', async ({ api }) => {
const first = await (await api.get('/users?limit=5')).json();
expect(first.cursor).toBeDefined();
const second = await (await api.get(`/users?limit=5&cursor=${first.cursor}`)).json();
const overlap = first.items.some((u: any) => second.items.find((x: any) => x.id === u.id));
expect(overlap).toBe(false);
});
authedRequest('GET /users with limit=101 returns 400', async ({ api }) => {
const res = await api.get('/users?limit=101');
expect(res.status()).toBe(400);
});
test('GET /users without auth returns 401', async ({ playwright }) => {
const api = await playwright.request.newContext({ baseURL: process.env.BASE_URL });
const res = await api.get('/users');
expect(res.status()).toBe(401);
await api.dispose();
});
authedRequest('POST /users valid returns 201 with User schema', async ({ api }) => {
const res = await api.post('/users', { data: { email: `u-${Date.now()}@x.io`, password: 'Pass1234', age: 25 } });
expect(res.status()).toBe(201);
const body = await res.json();
expect(validateUser(body), JSON.stringify(validateUser.errors)).toBe(true);
});
authedRequest('POST /users duplicate email returns 409', async ({ api }) => {
const email = `dup-${Date.now()}@x.io`;
await api.post('/users', { data: { email, password: 'Pass1234', age: 25 } });
const dup = await api.post('/users', { data: { email, password: 'Pass1234', age: 25 } });
expect(dup.status()).toBe(409);
});
```
## Spec gaps
- GET /users documents no 400, so the behaviour for limit=101 (reject vs clamp to 100) is a guess: document it.
- POST /users has no documented 429: does rate limiting exist? If yes, document it; if no, confirm and remove from CI alerts.
- 200 response on GET /users doesn't document UserPage's `cursor` field shape (nullable string vs always present): the pagination test assumes always-defined.
- No 5xx responses documented anywhere; production WILL return 503 during rolling deploys. Add and write a retry test.
- Auth fixture assumes a static `TEST_BEARER` env var; for refresh-token flows, add a token rotation step in the fixture.Common pitfalls
- Model writes schema validation by inline-redefining the schema instead of $ref: refs are essential for spec drift detection.
- Pagination test asserts a fixed page size instead of behavior: review whether the test would catch a regression to 'returns all 10000 rows'.
- Auth fixture gets duplicated across test files instead of a single shared fixture: extract immediately.
- Rate limit tests pass against a non-rate-limited staging env and fail in prod. Run them in an env that actually has limits enabled.
Tips
- When the spec changes, re-run the prompt and diff the test plan against the previous version: you'll see exactly which test cases need updating.
- Use the 'Spec gaps' section as your bug-tracker for the API team: these are real ambiguities that hurt every consumer.
- For OAuth flows, generate the auth fixture separately (it's complex enough to deserve its own prompt run).
- Pair this prompt with `api-rate-limiting-tests` to deepen 429 coverage.
FAQ
What schema validation library should I use?
Ajv (Node.js) for JSON Schema is the standard. For Pact-style contract tests, use Pact directly. For Python, jsonschema. For Java, the validator that ships with REST Assured. The principle, validate against the original spec, not a copy, is more important than the library.
How do I handle auth in CI without leaking real credentials?
Use a dedicated test tenant with short-lived tokens. Inject via env vars (never commit). Prefer CI OIDC federation or short-lived tokens minted per run; avoid long-lived static tokens.
Should I do contract testing (Pact) instead of API tests?
Both, ideally. Contract tests verify consumer/provider compatibility. API tests verify business logic and edge cases. Contracts catch breaking changes faster; API tests catch logic bugs the spec can't express.
What about generating client mocks from the spec?
Tools like Prism (Stoplight) can mock from an OpenAPI spec: useful for parallel development. But mocks drift from real behavior; always have at least one test suite hitting the real backend.