Use Cases

API Test Automation with Claude Code: A QA Practical Guide

API test automation using Claude Code. A QA practical guide. Includes practical code examples.

Putting API Test Automation Into Practice With Claude Code

Comprehensive testing is essential to guarantee API quality. With Claude Code, you can automate everything from test-case design to mock generation and CI integration in one go.

Test Case Design

CRUD Tests for a REST API

> Create CRUD tests for the users API using Vitest + supertest.
> Cover happy-path, error, and boundary-value cases.
// tests/api/users.test.ts
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import request from 'supertest';
import { app } from '../../src/app';
import { resetDatabase, seedUsers } from '../helpers/db';

describe('Users API', () => {
  beforeEach(async () => {
    await resetDatabase();
    await seedUsers();
  });

  describe('GET /api/users', () => {
    it('returns a list of users', async () => {
      const res = await request(app)
        .get('/api/users')
        .expect(200);

      expect(res.body.data).toBeInstanceOf(Array);
      expect(res.body.data.length).toBeGreaterThan(0);
      expect(res.body.data[0]).toHaveProperty('id');
      expect(res.body.data[0]).toHaveProperty('name');
      expect(res.body.data[0]).not.toHaveProperty('password');
    });

    it('paginates correctly', async () => {
      const res = await request(app)
        .get('/api/users?page=1&limit=5')
        .expect(200);

      expect(res.body.data.length).toBeLessThanOrEqual(5);
      expect(res.body.meta).toHaveProperty('totalPages');
      expect(res.body.meta).toHaveProperty('currentPage', 1);
    });
  });

  describe('POST /api/users', () => {
    it('creates a new user', async () => {
      const newUser = {
        name: 'Test User',
        email: 'test@example.com',
        password: 'SecurePass123!',
      };

      const res = await request(app)
        .post('/api/users')
        .send(newUser)
        .expect(201);

      expect(res.body.data.name).toBe(newUser.name);
      expect(res.body.data.email).toBe(newUser.email);
    });

    it('returns 400 for an invalid email address', async () => {
      const res = await request(app)
        .post('/api/users')
        .send({ name: 'Test', email: 'invalid', password: 'Pass123!' })
        .expect(400);

      expect(res.body.errors).toBeDefined();
    });

    it('returns 409 for a duplicate email address', async () => {
      await request(app)
        .post('/api/users')
        .send({ name: 'User1', email: 'dup@example.com', password: 'Pass123!' });

      await request(app)
        .post('/api/users')
        .send({ name: 'User2', email: 'dup@example.com', password: 'Pass456!' })
        .expect(409);
    });
  });
});

Generating Mocks and Stubs

Testing Code That Depends on External APIs

> Create a mock for the Stripe payment API.
> Use MSW.
// tests/mocks/handlers.ts
import { http, HttpResponse } from 'msw';

export const handlers = [
  http.post('https://api.stripe.com/v1/charges', () => {
    return HttpResponse.json({
      id: 'ch_test_123',
      amount: 1000,
      currency: 'usd',
      status: 'succeeded',
    });
  }),

  http.post('https://api.stripe.com/v1/refunds', () => {
    return HttpResponse.json({
      id: 're_test_456',
      amount: 1000,
      status: 'succeeded',
    });
  }),
];

Contract Testing

Claude Code can also generate contract tests that verify the consistency between the API specification and the implementation. You can build tests that automatically compare responses against an OpenAPI schema.

Performance Testing

> Create a load-test script for the API using k6.
> Use a scenario that ramps up the load in stages.
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  stages: [
    { duration: '1m', target: 50 },
    { duration: '3m', target: 50 },
    { duration: '1m', target: 100 },
    { duration: '3m', target: 100 },
    { duration: '1m', target: 0 },
  ],
  thresholds: {
    http_req_duration: ['p(95)<500'],
    http_req_failed: ['rate<0.01'],
  },
};

Summary

With Claude Code, you can automate the entire API testing lifecycle, from design to implementation to CI integration. See the testing strategies guide and CI/CD pipeline setup for related topics.

For more on API testing, see the official Vitest documentation.

#Claude Code #API testing #automation #testing #quality assurance

Level up your Claude Code workflow

50 battle-tested prompt templates you can copy-paste into Claude Code right now.

Free

Free PDF: Claude Code Cheatsheet in 5 Minutes

Key commands, shortcuts, and prompt examples on a single printable page.

Download PDF
M

About the Author

Masa

Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.