AI for API Mocking: Generating Realistic Stubs for Development and Testing
How to use AI to generate consistent, realistic API mocks from specs and existing code — and keep them in sync as your API evolves.
Writing API mocks by hand is one of those tasks that feels simple until it isn’t. You need a mock for the /users/{id} endpoint. You stub out a response object. Then you discover the response includes a nested permissions array with its own structure, and the createdAt field is an ISO string with a specific timezone format, and there’s a metadata field that varies by account type. What started as five minutes of busywork turns into an hour of reverse-engineering the shape of a response you don’t control.
AI handles this well. Given a spec, a sample response, or even a description, it can generate realistic, consistent mocks across an entire API surface quickly. The key is knowing what to give it and how to structure the output.
Start with the spec, not the shape
The most reliable approach is to give the model your OpenAPI spec (or a relevant slice of it) and ask for mocks directly. If you’re using MSW (Mock Service Worker) for browser-based development and testing, the prompt structure is straightforward:
Here is a subset of our OpenAPI spec for the /users endpoints:
[paste the relevant paths/components from your openapi.yaml]
Generate MSW request handlers for all GET and POST endpoints.
For GET /users/{id}, return a realistic mock user object where:
- id is a UUID
- email matches the pattern user-{n}@example.com
- role is one of: "admin", "member", "viewer"
- createdAt is an ISO 8601 string in UTC
- permissions is an array of 1–3 objects matching the Permission schema
Use http.get() and http.post() from msw, return HttpResponse.json() with
http.StatusCode where available. Put all handlers in a single array export.
The spec does the heavy lifting. The model reads the type definitions, picks up field names and formats, and generates handlers that match the real API shape. You get something you’d have spent an hour writing:
// src/mocks/handlers/users.ts
import { http, HttpResponse } from "msw";
export const userHandlers = [
http.get("/api/users/:id", ({ params }) => {
return HttpResponse.json({
id: params.id,
email: `[email protected]`,
role: "member",
createdAt: "2025-11-14T09:23:00Z",
permissions: [
{ resource: "projects", action: "read" },
{ resource: "reports", action: "read" },
],
});
}),
http.post("/api/users", async ({ request }) => {
const body = await request.json();
return HttpResponse.json(
{
id: "b3e2f1a0-9c8d-4e7f-a6b5-c4d3e2f1a0b9",
email: (body as { email: string }).email,
role: "member",
createdAt: new Date().toISOString(),
permissions: [],
},
{ status: 201 }
);
}),
];
Add error branches explicitly
The first pass gives you happy-path handlers. That’s not enough for testing — you also need the failure modes. Ask for them separately, as a second prompt:
Now generate a second set of handlers that simulate error conditions
for the same endpoints:
- GET /users/{id} with id "not-found" should return 404 with { error: "User not found" }
- GET /users/{id} with id "forbidden" should return 403 with { error: "Insufficient permissions" }
- POST /users with email matching /.*@blocked\.com/ should return 422 with
{ error: "Email domain is not allowed", field: "email" }
- Any endpoint, if the request includes header "X-Simulate-Error: 500",
should return 500 with { error: "Internal server error" }
Export these as a separate errorHandlers array so they can be loaded
selectively in tests.
The separation matters. In development, you usually want the happy path. In tests, you want to exercise specific failure modes. Keeping them in separate arrays means you can compose them:
// test: wraps server.use(errorHandlers) around specific test cases
// dev: server.use(...userHandlers) with no error overrides
The X-Simulate-Error header pattern is worth using in development as well — it lets you trigger error states in the UI without changing your mock configuration, which is useful for testing error UI that’s otherwise hard to reach.
Generate realistic data variation
Static mocks break tests that depend on variation — a list endpoint that always returns the same two users is useless for pagination tests. Ask the model to generate a factory function:
Write a createMockUser(overrides?: Partial<User>) factory function.
The base user should have:
- id: a deterministic UUID based on a counter (use a module-level counter)
- email: user-{n}@example.com where n matches the counter
- role: randomly selected from ["admin", "member", "viewer"] with weights 10/70/20
- createdAt: a random date within the past two years
- permissions: 1–5 entries, randomly selected from a fixed set of 8 known permissions
The function should merge overrides over the base object. Export a
createMockUserList(count: number, overrides?: Partial<User>) helper as well.
A deterministic counter keeps your mock IDs stable across test runs — user-1, user-2, etc. — while the random data makes pagination and filtering tests meaningful. The override pattern is what makes the factory actually useful:
// Tests can pin just the fields they care about
const admin = createMockUser({ role: "admin" });
const noPermissions = createMockUser({ permissions: [] });
const users = createMockUserList(50); // realistic pagination test data
Keeping mocks in sync when the API changes
Mocks drift. The API evolves, the mock doesn’t, and six months later you have tests that pass against a shape the real API stopped returning in March. AI doesn’t solve the drift problem automatically, but it makes the update workflow tractable.
When an endpoint changes, give the model the diff and ask it to update the mock:
The User type changed in this PR:
- The `permissions` field was removed
- A new `roles` field was added: an array of { roleId: string, roleName: string, scope: "global" | "project" }
- `createdAt` is now returned as a Unix timestamp (number), not an ISO string
Update the mock user factory and all MSW handlers to match the new shape.
List every handler and factory function you modified.
The explicit “list every change” instruction matters. Without it, the model tends to update the obvious places and miss the factory function, or update the factory but not the error handlers. Requiring a change list makes it harder to silently miss something.
This prompt pattern also works in reverse — if you’ve written mocks first (contract testing against an agreed spec) and need to verify the real implementation matches, give the model both and ask it to report the discrepancies.
Use AI to audit your mock coverage
After you’ve built a mock layer, there’s a subtler problem: you don’t know what’s missing. The endpoint you’ve never needed in development doesn’t have a handler. Neither does the error case you haven’t thought to test.
A coverage audit prompt:
Here are my current MSW handlers:
[paste your handler exports]
Here is the full list of endpoints from our OpenAPI spec:
[paste the paths section]
List every endpoint in the spec that:
1. Has no handler in my mock layer
2. Has a handler but no error-case variant
3. Has a handler but the response schema doesn't match the spec
For each gap, describe what's missing and why it's likely to matter in tests.
This produces a gap list you can work through methodically. Some gaps are intentional — you don’t mock endpoints your app doesn’t call. But others are genuine blind spots: an error case you haven’t handled in the UI, a field you assumed was always present that’s actually optional.
The spec comparison is especially useful for catching schema drift you introduced when updating handlers manually without reading the full spec. Pasting a 300-line spec into a prompt is fast; auditing 300 lines of YAML against 15 handler files by hand is slow.
A practical workflow
Putting this together into a development process:
When adding a new feature that calls a new endpoint: Give the model the relevant spec slice and generate handlers before you write the client code. Work against the mock, then swap in the real API when it’s ready.
When an API changes: Paste the diff and run the update prompt. Require a change list. Review it.
Before a release: Run the coverage audit against the current spec. Prioritize filling gaps for endpoints your UI actually calls.
In CI: Separate your happy-path and error-case handler arrays so tests can selectively load failure scenarios without manual server configuration.
The pattern throughout is the same as in Task Decomposition for AI Coding Agents: one clear input, one bounded output, a verifiable result. You’re not asking the model to build your entire mock layer — you’re feeding it a spec slice and asking for a specific artifact. That scope is easy to validate and easy to fix when it’s wrong.
API mocks are infrastructure, not features. They should be comprehensive, consistent, and require no manual maintenance. AI gets you there faster than hand-writing every handler, and it stays useful when the API changes.