Catalogue / http-api-testing-patterns
http-api-testing-patterns
Older skill: source not recordedSignedBuilds isolated HTTP API tests with Supertest or Python httpx and pytest, covering REST and GraphQL contracts, schemas, authentication, cookies, database isolation, and error paths. Use when the user says "test this endpoint", "write Supertest tests", "test my FastAPI routes", "add API integration t…--- name: http-api-testing-patterns description: >- Builds isolated HTTP API tests with Supertest or Python httpx and pytest, covering REST and GraphQL contracts, schemas, authentication, cookies, database isolation, and error paths. Use when the user says "test this endpoint", "write Supertest tests", "test my FastAPI routes", "add API integration tests", or "check auth and error responses". Not for mutating a live production database, exposing real credentials, or running unapproved load tests. ---
Define the endpoint contract and isolation
Inspect routes, framework, validation, authentication, database dependencies, and installed test versions. Require owner-provided verified dependencies; do not fetch and execute missing packages. Confirm exact test edits, process starts, test data changes, file writes, and external requests before execution. Use disposable test databases and synthetic credentials; never point cleanup at production.
For each behavior specify method/path, headers/query/body, expected status and content type, response shape/value, side effects, and error format. Cover successful and malformed input, missing resource, authentication failure, insufficient authorization, and controlled upstream/server failure. Keep tests independent, use minimal seed data and factories, and group by endpoint behavior.
Supertest request and response workflow
Pass a verified Express app directly to Supertest where possible; explicit listeners require teardown. Use get/post/put/patch/delete as appropriate. send supplies JSON, set supplies headers, query supplies parameters, attach supplies multipart files, and field supplies multipart text. Check status first, content type next, then exact or partial body fields and array size/content.
An original in-memory endpoint and two behavior tests:
import express from 'express';
import request from 'supertest';
import { describe, it, expect } from 'vitest';
const app = express();
app.use(express.json());
app.post('/api/parcels', (req, res) => {
if (typeof req.body.destination !== 'string' || !req.body.destination.trim()) {
return res.status(400).json({ error: 'Invalid destination', field: 'destination' });
}
return res.status(201).json({ id: 17, destination: req.body.destination.trim() });
});
describe('parcel creation contract', () => {
it('returns the normalized parcel', async () => {
const response = await request(app).post('/api/parcels')
.send({ destination: ' Bergen ' }).expect('Content-Type', /json/).expect(201);
expect(response.body).toEqual({ id: 17, destination: 'Bergen' });
});
it('returns field-specific invalid input', async () => {
const response = await request(app).post('/api/parcels').send({}).expect(400);
expect(response.body).toMatchObject({ field: 'destination' });
});
});Use request(app).get('/api/parcels').query({page: 2, limit: 6}) for pagination, then assert the contract's limits and ordering. A local upload fixture can use attach('file', approvedPath).field('description', 'fixture'); assert filename, size/type, and stored-state rules. DELETE may return 204 with an empty body; validate the actual API rather than forcing JSON.
Authentication, cookies, and failure paths
Create synthetic login accounts in the isolated fixture. Assert login success before taking its test token, use a Bearer header for protected requests, and test absent, malformed, expired, and invalid credentials. Do not log token values. OAuth tests need controlled provider responses and state/redirect checks; live identity flows require independent approval.
For sessions, inspect Set-Cookie security attributes and reuse cookies through a test agent or explicit Cookie header. Test logout and cross-user access where applicable. Python clients retain cookies within their scoped lifecycle. Never confuse token possession with sufficient authorization.
Force known validation, not-found, and server failures; assert documented status/error/detail fields and absence of stack traces or secrets. FastAPI validation commonly returns 422, while a custom Express validation route may return 400. Test the endpoint's contract rather than treating these as interchangeable.
Python synchronous and asynchronous clients
Use FastAPI TestClient for approved in-process synchronous tests and close it via a context manager or yielding fixture. For installed modern httpx, use ASGITransport rather than assuming the removed AsyncClient(app=...) shortcut exists. ASGI lifespan startup needs explicit fixture handling where required.
import pytest
import pytest_asyncio
import httpx
from service import app # Replace with the actual tested application module.
@pytest_asyncio.fixture
async def api_client():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url='http://fixture') as client:
yield client
@pytest.mark.asyncio
async def test_parcel_input(api_client):
response = await api_client.post('/api/parcels', json={})
assert response.status_code == 422
assert isinstance(response.json()['detail'], list)Use params for query fields, headers for authentication/content type, json for bodies, and files plus data for multipart. Open fixtures with context managers; tmp_path can create an approved disposable file. A reusable authenticated client fixture should assert login success, attach only synthetic credentials, and close even after failure.
Isolate database and upstream state
Prefer rollback transactions or a disposable schema per test worker. When overriding a FastAPI database dependency, preserve the old overrides and restore them in finally; close sessions and dispose the engine. Create/drop metadata only on a verified isolated engine. SQLite memory databases need connection/thread settings matched to the framework, not a shared unexplained test.db. Verify a create response, then retrieve its returned ID and assert persisted fields.
An original dependency-lifecycle helper for a test fixture:
from contextlib import contextmanager
@contextmanager
def replace_dependency(app, original_dependency, replacement):
previous = dict(app.dependency_overrides)
app.dependency_overrides[original_dependency] = replacement
try:
yield
finally:
app.dependency_overrides.clear()
app.dependency_overrides.update(previous)Mock upstream behavior at the boundary with installed Vitest vi.mock or unittest.mock.patch against the actual module lookup path. Cover success, timeout, and failure. Reusable data factories should allow explicit overrides without leaking state. Do not mock the persistence behavior that the integration test intends to verify.
Validate schema and GraphQL semantics
For TypeScript use an installed Ajv validator, required fields and types, and reviewed additional-property policy. Email/date-time formats may require the installed version's separate format plugin; do not assume a schema's format keyword is checked automatically. Assert validation errors meaningfully.
For Python use the installed Pydantic API (v2 model_validate/field_validator or supported older equivalents) with nonblank names, numeric IDs, expected timestamp types, and email validation dependencies where provided. Schema parsing complements exact contract values rather than replacing them.
GraphQL tests post a query and variables to the actual endpoint, assert transport status, then inspect both data and errors. A 200 response can still contain GraphQL failure. Use a different fixture query, for example ParcelByCode with a code variable and id/destination selection; verify authorized data and error behavior in both Supertest and Python clients.
Measure and diagnose carefully
Use a monotonic timer, warmup/repetitions, and environment-specific budgets for response-time checks. The documented illustrative 100 ms threshold is not a universal SLA. In-process tests exclude real network conditions. Load testing needs a separately approved target, concurrency, duration, budget, and stop conditions.
For occupied ports, prefer in-process transport or an approved random-port listener (listen(0)), then close it. For database errors verify isolation, connectivity, fixture order, and engine cleanup. For slow tests mock irrelevant expensive work while retaining the behavior under test.
Inspect project scripts before choosing commands. Documented Bun fast-feedback options include --dots and --bail=1 for a selected API subset/file; verify local help and do not use Bun to run a Vitest-only suite blindly. pytest -x --tb=short tests/api/ is a targeted Python option when installed. Report actual test framework, scope, passed/failed checks, untested integration, and any stateful operations.
Never
- Point tests, seed data, or cleanup at a shared or production database; isolation is verified before the first request fires.
- Commit or log real tokens, passwords, or session cookies — synthetic credentials only, and never print token values.
- Run a load test or hit an external identity provider without separate approval of target, concurrency, and stop conditions.
- Mock the persistence layer an integration test exists to verify, or skip teardown of listeners, clients, and engines.
- Assume status-code conventions (400 versus 422, 204 versus 200) instead of testing the endpoint's actual contract.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 9.5 kB | 0c06094db983 |
| examples.json | 1.7 kB | f4eac93cc0bf |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.0 Current | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.