/api-testing-patterns
Comprehensive API testing patterns including contract testing, REST/GraphQL testing, and integration testing. Use when testing APIs or designing API test strategies.
$ npx -y skills add proffesor-for-testing/agentic-qe --skill api-testing-patterns --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
- You can call itInvoke it directly when you want it.
- Slash command
/api-testing-patterns
Context preview
The summary Claude sees to decide when to auto-load this skill.
Comprehensive API testing patterns including contract testing, REST/GraphQL testing, and integration testing. Use when testing APIs or designing API test strategies.
SKILL.md
api-testing-patterns.SKILL.mdname: api-testing-patterns
description: "Comprehensive API testing patterns including contract testing, REST/GraphQL testing, and integration testing. Use when testing APIs or designing API test strategies."
category: testing-methodologies
priority: high
tokenEstimate: 1200
agents: [qe-api-contract-validator, qe-test-generator, qe-performance-tester, qe-security-scanner]
implementation_status: optimized
optimization_version: 1.0
last_optimized: 2025-12-02
dependencies: []
quick_reference_card: true
tags: [api, rest, graphql, contract-testing, pact, integration, microservices]
trust_tier: 3
validation:
schema_path: schemas/output.json
validator_path: scripts/validate-config.json
eval_path: evals/api-testing-patterns.yaml
API Testing Patterns
<default_to_action> When testing APIs or designing API test strategy: 1. IDENTIFY testing level: contract, integration, or component 2. TEST the contract, not implementation (consumer perspective) 3. VALIDATE auth, input, errors, idempotency, concurrency 4. AUTOMATE in CI/CD with schema validation 5. MONITOR production APIs for contract drift
**Quick Pattern Selection:**
- Microservices → Consumer-driven contracts (Pact)
- REST APIs → CRUD + pagination + filtering tests
- GraphQL → Query validation + complexity limits
- External deps → Mock with component testing
- Performance → Load test critical endpoints
**Critical Success Factors:**
- APIs are contracts - test from consumer perspective
- Always test error scenarios, not just happy paths
- Version your API tests to prevent breaking changes
</default_to_action>
Quick Reference Card
When to Use
- Testing REST or GraphQL APIs
- Validating microservice contracts
- Designing API test strategies
- Preventing breaking API changes
Testing Levels
| Level | Purpose | Dependencies | Speed | |-------|---------|--------------|-------| | Contract | Provider-consumer agreement | None | Fast | | Component | API in isolation | Mocked | Fast | | Integration | Real dependencies | Database, services | Slower |
Critical Test Scenarios
| Scenario | Must Test | Example | |----------|----------|---------| | Auth | 401/403 handling | Expired token, wrong user | | Input | 400 validation | Missing fields, wrong types | | Errors | 500 graceful handling | DB down, timeout | | Idempotency | Duplicate prevention | Same idempotency key | | Concurrency | Race conditions | Parallel checkout |
Tools
- **Contract**: Pact, Spring Cloud Contract
- **REST**: Supertest, REST-assured, Playwright
- **Load**: k6, Artillery, JMeter
Agent Coordination
- `qe-api-contract-validator`: Validate contracts, detect breaking changes
- `qe-test-generator`: Generate tests from OpenAPI spec
- `qe-performance-tester`: Load test endpoints
- `qe-security-scanner`: API security testing
---
Contract Testing
**Pattern: Consumer-Driven Contracts**
// Consumer defines expectations
const contract = {
request: { method: 'POST', path: '/orders', body: { productId: 'abc', quantity: 2 } },
response: { status: 201, body: { orderId: 'string', total: 'number' } }
};
// Provider must fulfill
test('order API meets contract', async () => {
const response = await api.post('/orders', { productId: 'abc', quantity: 2 });
expect(response.status).toBe(201);
expect(response.body).toMatchSchema({
orderId: expect.any(String),
total: expect.any(Number)
});
});**When:** Microservices, distributed systems, third-party integrations
---
Critical Test Patterns
Authentication & Authorization
describe('Auth', () => {
it('rejects without token', async () => {
expect((await api.get('/orders')).status).toBe(401);
});
it('rejects expired token', async () => {
const expired = generateExpiredToken();
expect((await api.get('/orders', { headers: { Authorization: `Bearer ${expired}` } })).status).toBe(401);
});
it('blocks cross-user access', async () => {
const userAToken = generateToken({ userId: 'A' });
expect((await api.get('/orders/user-B-order', { headers: { Authorization: `Bearer ${userAToken}` } })).status).toBe(403);
});
});Input Validation
describe('Validation', () => {
it('validates required fields', async () => {
const response = await api.post('/orders', { quantity: 2 }); // Missing productId
expect(response.status).toBe(400);
expect(response.body.errors).toContain('productId is required');
});
it('validates types', async () => {
expect((await api.post('/orders', { productId: 'abc', quantity: 'two' })).status).toBe(400);
});
it('validates ranges', async () => {
expect((await api.post('/orders', { productId: 'abc', quantity: -5 })).status).toBe(400);
});
});Idempotency
it('prevents duplicates with idempotency key', async () => {
const key = 'unique-123';
const data = { productId: 'abc', quantity: 2 };
const r1 = await api.post('/orders', data, { headers: { 'Idempotency-Key': key } });
const r2 = await api.post('/orders', data, { headers: { 'Idempotency-Key': key } });
expect(r1.body.orderId).toBe(r2.body.orderId); // Same order
});Concurrency
it('handles race condition on inventory', async () => {
const promises = Array(10).fill().map(() =>
api.post('/orders', { productId: 'abc', quantity: 1 })
);
const responses = await Promise.all(promises);
const successful = responses.filter(r => r.status === 201);
const inventory = await db.inventory.findById('abc');
expect(inventory.quantity).toBe(initialQuantity - successful.length);
});---
REST CRUD Pattern
describe('Product CRUD', () => {
let productId;
it('CREATE', async () => {
const r = await api.post('/products', { name: 'Widget', price: 10 });
expect(r.status).toBe(201);
productId = r.body.id;
});
it('READ', async () => {
const r = await api.get(`/products/${productId}`);
expect(r.body.name).toBe('WidgRead more
name: api-testing-patterns description: "Comprehensive API testing patterns including contract testing, REST/GraphQL testing, and integration testing. Use when testing APIs or designing API test strategies." category: testing-methodologies priority: high tokenEstimate: 1200 agents: [qe-api-contract-validator, qe-test-generator, qe-performance-tester, qe-security-scanner] implementation_status: optimized optimization_version: 1.0 last_optimized: 2025-12-02 dependencies: [] quick_reference_card: true tags: [api, rest, graphql, contract-testing, pact, integration, microservices] trust_tier: 3 validation: schema_path: schemas/output.json validator_path: scripts/validate-config.json eval_path: evals/api-testing-patterns.yaml
API Testing Patterns
<default_to_action> When testing APIs or designing API test strategy: 1. IDENTIFY testing level: contract, integration, or component 2. TEST the contract, not implementation (consumer perspective) 3. VALIDATE auth, input, errors, idempotency, concurrency 4. AUTOMATE in CI/CD with schema validation 5. MONITOR production APIs for contract drift
**Quick Pattern Selection:**
- Microservices → Consumer-driven contracts (Pact)
- REST APIs → CRUD + pagination + filtering tests
- GraphQL → Query validation + complexity limits
- External deps → Mock with component testing
- Performance → Load test critical endpoints
**Critical Success Factors:**
- APIs are contracts - test from consumer perspective
- Always test error scenarios, not just happy paths
- Version your API tests to prevent breaking changes
</default_to_action>
Quick Reference Card
When to Use
- Testing REST or GraphQL APIs
- Validating microservice contracts
- Designing API test strategies
- Preventing breaking API changes
Testing Levels
| Level | Purpose | Dependencies | Speed | |-------|---------|--------------|-------| | Contract | Provider-consumer agreement | None | Fast | | Component | API in isolation | Mocked | Fast | | Integration | Real dependencies | Database, services | Slower |
Critical Test Scenarios
| Scenario | Must Test | Example | |----------|----------|---------| | Auth | 401/403 handling | Expired token, wrong user | | Input | 400 validation | Missing fields, wrong types | | Errors | 500 graceful handling | DB down, timeout | | Idempotency | Duplicate prevention | Same idempotency key | | Concurrency | Race conditions | Parallel checkout |
Tools
- **Contract**: Pact, Spring Cloud Contract
- **REST**: Supertest, REST-assured, Playwright
- **Load**: k6, Artillery, JMeter
Agent Coordination
- `qe-api-contract-validator`: Validate contracts, detect breaking changes
- `qe-test-generator`: Generate tests from OpenAPI spec
- `qe-performance-tester`: Load test endpoints
- `qe-security-scanner`: API security testing
---
Contract Testing
**Pattern: Consumer-Driven Contracts**
// Consumer defines expectations
const contract = {
request: { method: 'POST', path: '/orders', body: { productId: 'abc', quantity: 2 } },
response: { status: 201, body: { orderId: 'string', total: 'number' } }
};
// Provider must fulfill
test('order API meets contract', async () => {
const response = await api.post('/orders', { productId: 'abc', quantity: 2 });
expect(response.status).toBe(201);
expect(response.body).toMatchSchema({
orderId: expect.any(String),
total: expect.any(Number)
});
});**When:** Microservices, distributed systems, third-party integrations
---
Critical Test Patterns
Authentication & Authorization
describe('Auth', () => {
it('rejects without token', async () => {
expect((await api.get('/orders')).status).toBe(401);
});
it('rejects expired token', async () => {
const expired = generateExpiredToken();
expect((await api.get('/orders', { headers: { Authorization: `Bearer ${expired}` } })).status).toBe(401);
});
it('blocks cross-user access', async () => {
const userAToken = generateToken({ userId: 'A' });
expect((await api.get('/orders/user-B-order', { headers: { Authorization: `Bearer ${userAToken}` } })).status).toBe(403);
});
});Input Validation
describe('Validation', () => {
it('validates required fields', async () => {
const response = await api.post('/orders', { quantity: 2 }); // Missing productId
expect(response.status).toBe(400);
expect(response.body.errors).toContain('productId is required');
});
it('validates types', async () => {
expect((await api.post('/orders', { productId: 'abc', quantity: 'two' })).status).toBe(400);
});
it('validates ranges', async () => {
expect((await api.post('/orders', { productId: 'abc', quantity: -5 })).status).toBe(400);
});
});Idempotency
it('prevents duplicates with idempotency key', async () => {
const key = 'unique-123';
const data = { productId: 'abc', quantity: 2 };
const r1 = await api.post('/orders', data, { headers: { 'Idempotency-Key': key } });
const r2 = await api.post('/orders', data, { headers: { 'Idempotency-Key': key } });
expect(r1.body.orderId).toBe(r2.body.orderId); // Same order
});Concurrency
it('handles race condition on inventory', async () => {
const promises = Array(10).fill().map(() =>
api.post('/orders', { productId: 'abc', quantity: 1 })
);
const responses = await Promise.all(promises);
const successful = responses.filter(r => r.status === 201);
const inventory = await db.inventory.findById('abc');
expect(inventory.quantity).toBe(initialQuantity - successful.length);
});---
REST CRUD Pattern
describe('Product CRUD', () => {
let productId;
it('CREATE', async () => {
const r = await api.post('/products', { name: 'Widget', price: 10 });
expect(r.status).toBe(201);
productId = r.body.id;
});
it('READ', async () => {
const r = await api.get(`/products/${productId}`);
expect(r.body.name).toBe('WidgAI-powered quality engineering agents that generate tests, find coverage gaps, detect flaky tests, and learn your codebase patterns — across 11 coding agent platforms.
Repo: proffesor-for-testing/agentic-qe
Other skills on agentic-qe.
- /a11y-ally
Use when running comprehensive WCAG accessibility audits with axe-core + pa11y + Lighthouse, generating context-aware remediation, or testing video accessibility. Supports 3-tier browser cascade with graceful degradation.
Open skill - /accessibility-testing
WCAG 2.2 compliance testing, screen reader validation, and inclusive design verification. Use when ensuring legal compliance (ADA, Section 508), testing for disabilities, or building accessible applications for 1 billion disabled users globally.
Open skill - /agentdb-advanced
Master advanced AgentDB features including QUIC synchronization, multi-database management, custom distance metrics, hybrid search, and distributed systems integration. Use when building distributed AI systems, multi-agent coordination, or advanced vector search applications.
Open skill - /agentdb-learning
Create and train AI learning plugins with AgentDB's 9 reinforcement learning algorithms. Includes Decision Transformer, Q-Learning, SARSA, Actor-Critic, and more. Use when building self-learning agents, implementing RL, or optimizing agent behavior through experience.
Open skill - /agentdb-memory-patterns
Implement persistent memory patterns for AI agents using AgentDB. Includes session memory, long-term storage, pattern learning, and context management. Use when building stateful agents, chat systems, or intelligent assistants.
Open skill - /agentdb-optimization
Optimize AgentDB performance with quantization (4-32x memory reduction), HNSW indexing (150x faster search), caching, and batch operations. Use when optimizing memory usage, improving search speed, or scaling to millions of vectors.
Open skill

