Back to Skills

api-testing-patterns

proffesor-for-testing
Updated Today
47 views
99
21
99
View on GitHub
Otherapirestgraphqlcontract-testingpactintegrationmicroservices

About

This Claude Skill provides comprehensive API testing patterns for contract testing, REST/GraphQL validation, and integration testing. Use it when designing API test strategies or implementing automated API testing in CI/CD pipelines. It helps developers validate contracts, test authentication, handle errors, and monitor for production API drift.

Documentation

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

LevelPurposeDependenciesSpeed
ContractProvider-consumer agreementNoneFast
ComponentAPI in isolationMockedFast
IntegrationReal dependenciesDatabase, servicesSlower

Critical Test Scenarios

ScenarioMust TestExample
Auth401/403 handlingExpired token, wrong user
Input400 validationMissing fields, wrong types
Errors500 graceful handlingDB down, timeout
IdempotencyDuplicate preventionSame idempotency key
ConcurrencyRace conditionsParallel 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('Widget');
  });

  it('UPDATE', async () => {
    const r = await api.put(`/products/${productId}`, { price: 12 });
    expect(r.body.price).toBe(12);
  });

  it('DELETE', async () => {
    expect((await api.delete(`/products/${productId}`)).status).toBe(204);
    expect((await api.get(`/products/${productId}`)).status).toBe(404);
  });
});

Best Practices

✅ Do This

  • Test from consumer perspective
  • Use schema validation (not exact values)
  • Test error scenarios extensively
  • Version API tests
  • Automate in CI/CD

❌ Avoid This

  • Testing implementation, not contract
  • Ignoring HTTP semantics (status codes)
  • No negative testing
  • Asserting on field order or extra fields
  • Slow tests (mock external services)

Agent-Assisted API Testing

// Validate contracts
await Task("Contract Validation", {
  spec: 'openapi.yaml',
  endpoint: '/orders',
  checkBreakingChanges: true
}, "qe-api-contract-validator");

// Generate tests from spec
await Task("Generate API Tests", {
  spec: 'openapi.yaml',
  coverage: 'comprehensive',
  include: ['happy-paths', 'input-validation', 'auth-scenarios', 'error-handling']
}, "qe-test-generator");

// Load test
await Task("API Load Test", {
  endpoint: '/orders',
  rps: 1000,
  duration: '5min'
}, "qe-performance-tester");

// Security scan
await Task("API Security Scan", {
  spec: 'openapi.yaml',
  checks: ['sql-injection', 'xss', 'broken-auth', 'rate-limiting']
}, "qe-security-scanner");

Agent Coordination Hints

Memory Namespace

aqe/api-testing/
├── contracts/*        - API contract definitions
├── generated-tests/*  - Generated test suites
├── validation/*       - Contract validation results
└── performance/*      - Load test results

Fleet Coordination

const apiFleet = await FleetManager.coordinate({
  strategy: 'contract-testing',
  agents: ['qe-api-contract-validator', 'qe-test-generator', 'qe-test-executor'],
  topology: 'mesh'
});

await apiFleet.execute({
  services: [
    { name: 'orders-api', consumers: ['checkout-ui', 'admin-api'] },
    { name: 'payment-api', consumers: ['orders-api'] }
  ]
});

Related Skills


Remember

API testing = verifying contracts and behavior, not implementation. Focus on what matters to consumers: correct responses, proper error handling, acceptable performance.

With Agents: Agents automate contract validation, generate comprehensive test suites from specs, and monitor production APIs for drift. Use agents to maintain API quality at scale.

Quick Install

/plugin add https://github.com/proffesor-for-testing/agentic-qe/tree/main/api-testing-patterns

Copy and paste this command in Claude Code to install this skill

GitHub 仓库

proffesor-for-testing/agentic-qe
Path: .claude/skills/api-testing-patterns
agenticqeagenticsfoundationagentsquality-engineering

Related Skills

evaluating-llms-harness

Testing

This Claude Skill runs the lm-evaluation-harness to benchmark LLMs across 60+ standardized academic tasks like MMLU and GSM8K. It's designed for developers to compare model quality, track training progress, or report academic results. The tool supports various backends including HuggingFace and vLLM models.

View skill

langchain

Meta

LangChain is a framework for building LLM applications using agents, chains, and RAG pipelines. It supports multiple LLM providers, offers 500+ integrations, and includes features like tool calling and memory management. Use it for rapid prototyping and deploying production systems like chatbots, autonomous agents, and question-answering services.

View skill

huggingface-accelerate

Development

HuggingFace Accelerate provides the simplest API for adding distributed training to PyTorch scripts with just 4 lines of code. It offers a unified interface for multiple distributed training frameworks like DeepSpeed, FSDP, and DDP while handling automatic device placement and mixed precision. This makes it ideal for developers who want to quickly scale their PyTorch training across multiple GPUs or nodes without complex configuration.

View skill

nestjs

Meta

This skill provides NestJS development standards and architectural patterns for building domain-centric applications. It covers modular design, dependency injection, decorator patterns, and key framework features like controllers, services, middleware, and interceptors. Use it when developing NestJS applications, implementing APIs, configuring microservices, or integrating with databases.

View skill