Generate a typed API client from an OpenAPI or GraphQL spec with a maintained generator or a small wrapper with timeouts, typed errors and safe retries.
---
name: api-client
description: Creates a typed API client from an OpenAPI 3.x or Swagger 2.0 spec or a GraphQL schema - preferably with an established generator (openapi-typescript with openapi-fetch, OpenAPI Generator, GraphQL Code Generator), otherwise a small hand-written TypeScript, Python or Go wrapper - with timeouts, typed errors, auth from environment variables and retries only for idempotent requests. Use when asked to generate an API client or SDK, type an API, or wrap REST or GraphQL endpoints.
compatibility: Generators need Node.js (openapi-typescript, GraphQL Code Generator) or Java 11+ (OpenAPI Generator). The hand-written TypeScript client needs a runtime with fetch and AbortSignal.timeout (Node 18+ or a modern browser).
metadata:
version: "1.0.0"
---
# API Client Generator
Turns an API description into client code the project can call safely. The spec is the source of truth: endpoints, parameters and types come from it, never from guesses about how the API probably works.
## Inputs to collect
- **The spec**: a local `openapi.yaml`/`openapi.json` (OpenAPI 3.x or Swagger 2.0) or GraphQL schema/introspection file. If the user only has a URL, ask before fetching it, and fetch only the machine-readable spec (for example `/openapi.json`), not arbitrary HTML docs. If there is no spec, ask for one or for a list of the endpoints to wrap; do not infer an API from marketing pages.
- Target language and runtime (TypeScript in Node or browser, Python, Go) and the HTTP library already in the project.
- Auth scheme from the spec's `securitySchemes` (bearer, API key header, OAuth2) and the environment variable that will hold the secret.
- Where generated code should live and whether it is committed or regenerated in CI.
## Workflow
1. **Validate the spec** before generating: parse it, check the OpenAPI version, `servers`, `securitySchemes` and that referenced schemas resolve. Report problems instead of papering over them.
2. **Prefer a maintained generator** (ask before adding dependencies):
- TypeScript types + thin fetch client: `npx openapi-typescript ./openapi.yaml -o ./src/api/schema.d.ts`, then `openapi-fetch`: `const client = createClient<paths>({ baseUrl })`; each call returns `{ data, error, response }`.
- Full SDKs in many languages: `npx @openapitools/openapi-generator-cli generate -i openapi.yaml -g typescript-fetch -o src/api` (or `-g python`, `-g go`); needs Java 11+.
- GraphQL: GraphQL Code Generator with the plugin set matching the project's client.
3. **Otherwise hand-write a small wrapper** (pattern below): one request function with base URL handling, JSON encoding, auth header from a callback, a timeout, a typed error carrying status and body, and retries limited to idempotent methods (GET, PUT, DELETE) on 408/429/502/503/504 or network errors, with backoff and `Retry-After`. POST and PATCH are never retried automatically, because repeating them can create duplicates; retry those only if the API supports idempotency keys.
4. **Keep secrets out of code**: tokens come from env or a secret store at runtime; never embed them in generated files or ship server tokens to browser bundles.
5. **Check the result**: type-check (`tsc --noEmit`, `mypy`, `go vet`), and if a sandbox or mock server is available, call one read-only endpoint. Report what was actually run.
## Hand-written TypeScript pattern
```ts
export interface User { id: string; email: string; name: string }
export interface CreateUserInput { email: string; name: string }
export class ApiError extends Error {
readonly status: number;
readonly body: unknown;
constructor(status: number, body: unknown, message: string) {
super(message);
this.name = 'ApiError';
this.status = status;
this.body = body;
}
}
type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
// RFC 9110: GET, HEAD, OPTIONS, PUT and DELETE are idempotent; POST and PATCH are not.
const IDEMPOTENT = new Set<Method>(['GET', 'PUT', 'DELETE']);
const RETRYABLE_STATUS = new Set([408, 429, 502, 503, 504]);
export interface ClientOptions {
baseUrl: string;
getToken?: () => string | undefined; // e.g. () => process.env.API_TOKEN
timeoutMs?: number;
maxRetries?: number;
fetchImpl?: typeof fetch;
}
export class ApiClient {
private readonly opts: Required<Omit<ClientOptions, 'getToken'>> & Pick<ClientOptions, 'getToken'>;
constructor(opts: ClientOptions) {
this.opts = { timeoutMs: 10_000, maxRetries: 2, fetchImpl: fetch, ...opts };
}
async request<T>(method: Method, path: string, body?: unknown, query?: Record<string, string | number | undefined>): Promise<T> {
const url = new URL(path.replace(/^\//, ''), this.opts.baseUrl.endsWith('/') ? this.opts.baseUrl : this.opts.baseUrl + '/');
for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined) url.searchParams.set(k, String(v));
const headers: Record<string, string> = { accept: 'application/json' };
if (body !== undefined) headers['content-type'] = 'application/json';
const token = this.opts.getToken?.();
if (token) headers.authorization = `Bearer ${token}`;
const attempts = IDEMPOTENT.has(method) ? this.opts.maxRetries + 1 : 1;
for (let attempt = 1; ; attempt++) {
let res: Response;
try {
res = await this.opts.fetchImpl(url, {
method, headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(this.opts.timeoutMs),
});
} catch (err) {
if (attempt < attempts) { await delay(backoff(attempt)); continue; }
throw err;
}
if (res.ok) return (res.status === 204 ? undefined : await res.json()) as T;
if (attempt < attempts && RETRYABLE_STATUS.has(res.status)) {
await delay(retryAfterMs(res.headers.get('retry-after')) ?? backoff(attempt));
continue;
}
const text = await res.text();
let parsed: unknown = text;
try { parsed = JSON.parse(text); } catch { /* keep text */ }
throw new ApiError(res.status, parsed, `${method} ${url.pathname} failed with ${res.status}`);
}
}
}
export class UsersApi {
private readonly client: ApiClient;
constructor(client: ApiClient) { this.client = client; }
list(params?: { page?: number; limit?: number }) { return this.client.request<User[]>('GET', '/users', undefined, params); }
get(id: string) { return this.client.request<User>('GET', `/users/${encodeURIComponent(id)}`); }
create(data: CreateUserInput) { return this.client.request<User>('POST', '/users', data); }
update(id: string, data: Partial<CreateUserInput>) { return this.client.request<User>('PATCH', `/users/${encodeURIComponent(id)}`, data); }
remove(id: string) { return this.client.request<void>('DELETE', `/users/${encodeURIComponent(id)}`); }
}
const delay = (ms: number) => new Promise(r => setTimeout(r, ms));
const backoff = (attempt: number) => Math.min(1000 * 2 ** (attempt - 1), 8000) * (0.5 + Math.random() / 2);
function retryAfterMs(h: string | null): number | undefined {
if (!h) return undefined;
const s = Number(h);
if (Number.isFinite(s)) return s * 1000;
const t = Date.parse(h);
return Number.isNaN(t) ? undefined : Math.max(0, t - Date.now());
}
```
Usage: `const users = new UsersApi(new ApiClient({ baseUrl: 'https://api.example.com/v1', getToken: () => process.env.API_TOKEN }));`
## Output format
- Generated or written files and the command used to produce them.
- Notes: auth setup, env vars, retry and timeout defaults, endpoints skipped or unsupported.
- Checks run (type-check, mock-server call) with their actual results.
## Limitations
- A client is only as accurate as the spec; flag endpoints whose documented responses look incomplete.
- Pagination, streaming, file uploads and webhooks need endpoint-specific handling; list them rather than guessing.
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A TypeScript backend needs to call a partner's Users REST API described by an openapi.yaml the partner shared; the team wants types and sensible failure handling.
Create a TypeScript client for ./specs/users-openapi.yaml (OpenAPI 3.1, bearer auth, base https://api.example.com/v1). Endpoints: GET /users, GET /users/{id}, POST /users, PATCH /users/{id}, DELETE /users/{id}. Token is in API_TOKEN. Don't add Java.A spec check first (version, servers, bearer securityScheme, resolvable schemas). Because Java is excluded, either openapi-typescript + openapi-fetch (after asking to add those dev dependencies) with the exact command, or the hand-written pattern from the skill: UsersApi list/get/create/update/remove over an ApiClient that reads the token via getToken, times out requests, throws ApiError with status and parsed body, and retries GET/PUT/DELETE on 408/429/502/503/504 but never POST/PATCH. Ends with `tsc --noEmit` results and any endpoints needing special handling.
AI Agent Skills are reusable workflow packages that extend your AI coding assistant with multi-step capabilities. Install api-client by following these steps.
SKILL.md inside, in the location documented by your client. Do not assume every AI application reads the same directory.Requires an Agent Skills-compatible client; supported locations and activation vary by version. Read the SKILL.md setup guide. MCP connects tools and data and does not, by itself, install a skill.