agentleFS
agentsdanceagentsdance/agentskills/skills/api-contract-tester/SKILL.md

api-contract-tester

Skill3 starsChanged 11 months agoApache-2.0View on GitHub

Test API contracts and ensure compatibility. Use when the user needs to validate API schemas, test backward compatibility, or implement contract testing.

  • Installs packages

The file

Files
SKILL.md

API Contract Tester

Validate API contracts between services.

Pact (Consumer-Driven Contracts)

Consumer Test

import { Pact } from '@pact-foundation/pact';
import { getUserById } from '../client/userClient';

const provider = new Pact({
  consumer: 'frontend',
  provider: 'user-service',
  port: 1234,
});

describe('User API Contract', () => {
  beforeAll(() => provider.setup());
  afterAll(() => provider.finalize());
  afterEach(() => provider.verify());

  it('should get user by id', async () => {
    // Define expected interaction
    await provider.addInteraction({
      state: 'user with id 1 exists',
      uponReceiving: 'a request for user 1',
      withRequest: {
        method: 'GET',
        path: '/api/users/1',
        headers: { Accept: 'application/json' },
      },
      willRespondWith: {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
        body: {
          id: 1,
          name: Matchers.string('John Doe'),
          email: Matchers.email(),
        },
      },
    });

    // Make the actual call
    const user = await getUserById(1);

    expect(user.id).toBe(1);
    expect(user.name).toBeDefined();
  });
});

Provider Verification

import { Verifier } from '@pact-foundation/pact';

describe('User Service Contract Verification', () => {
  it('validates contract with frontend', async () => {
    await new Verifier({
      provider: 'user-service',
      providerBaseUrl: 'http://localhost:3000',
      pactUrls: ['./pacts/frontend-user-service.json'],
      stateHandlers: {
        'user with id 1 exists': async () => {
          await createTestUser({ id: 1, name: 'John Doe' });
        },
      },
    }).verifyProvider();
  });
});

OpenAPI Schema Validation

import SwaggerParser from '@apidevtools/swagger-parser';
import Ajv from 'ajv';

async function validateResponse(response, operationId) {
  const api = await SwaggerParser.dereference('./openapi.yaml');
  const schema = findResponseSchema(api, operationId, response.status);

  const ajv = new Ajv();
  const validate = ajv.compile(schema);

  if (!validate(response.data)) {
    throw new Error(`Response validation failed: ${JSON.stringify(validate.errors)}`);
  }
}

// Usage in tests
it('should return valid user response', async () => {
  const response = await api.get('/users/1');
  await validateResponse(response, 'getUserById');
});

Prism Mock Server

# Install
npm install -g @stoplight/prism-cli

# Start mock server from OpenAPI spec
prism mock openapi.yaml

# Validate requests
prism proxy openapi.yaml http://localhost:3000

Contract Test Types

TypeDescriptionWhen to Use
Consumer-drivenConsumer defines contractMicroservices
Provider-drivenProvider defines contractPublic APIs
Schema validationValidate against specAny API

CI Integration

jobs:
  contract-test:
    steps:
      - name: Run consumer tests
        run: npm run test:contract

      - name: Publish pacts
        run: |
          npx pact-broker publish ./pacts \
            --consumer-app-version=${{ github.sha }} \
            --broker-base-url=${{ secrets.PACT_BROKER_URL }}

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.