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: '[email protected]',
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: '[email protected]', password: 'Pass123!' });
await request(app)
.post('/api/users')
.send({ name: 'User2', email: '[email protected]', 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.
Free PDF: Claude Code Cheatsheet in 5 Minutes
Just enter your email and we'll send you the single-page A4 cheatsheet right away.
We handle your data with care and never send spam.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
7 Deployment Checks Before You Publish a Multilingual Claude Code Article Every Day
A practical checklist for publishing daily multilingual Claude Code articles without missing locales, breaking CTAs, or shipping stale pages.
Codex Automations for Content Ops: A Daily Revenue Workflow for Claude Code Sites
Use Codex Automations to turn analytics, article updates, CTA improvements, deployment, and verification into a daily revenue workflow.
Claude Code × GCP Cloud Functions Complete Guide | Rapid Serverless Function Development
Streamline GCP Cloud Functions with Claude Code. Implement HTTP/Pub/Sub/Firestore triggers, local testing, and deployment automation with real-world code examples from Masa's experience.
Related Products
50 Battle-Tested Claude Code Prompt Templates
Copy, paste, ship. 50 production-ready prompts.
Use proven prompts for code review, refactoring, testing, documentation, debugging, architecture, and incident response.
The Complete Claude Code Setup & Configuration Guide
From install to team-ready workflow.
A practical guide to installation, CLAUDE.md, hooks, MCP servers, permissions, IDE setup, and CI/CD workflows.