Generate robust API client code: typed fetch wrappers, explicit error types, timeouts, retries only for safe requests with backoff, redacted logging, caching and testable mocks.
.devin/rules/windsurf-api-integration-patterns.md. Downloaded files need to be placed in that repository path.---
trigger: glob
globs: "**/*"
---
When generating code that calls HTTP APIs:
## Typed fetch wrapper
- Wrap `fetch` in one module that sets the base URL, headers and auth, parses JSON, and returns typed data. Validate responses from external APIs with a schema before trusting the type.
## Errors
- Throw (or return) a dedicated error type that carries `status`, the request method/URL and a parsed error body, so callers can branch on status codes. Treat non-2xx responses as errors; `fetch` itself only rejects on network failure.
## Timeouts
- Give every request a timeout with `AbortSignal.timeout(ms)` (combine with a caller's signal using `AbortSignal.any([...])`). Distinguish timeouts (`TimeoutError`) from caller cancellations (`AbortError`).
## Retries
- Retry only idempotent requests (GET, HEAD, PUT, DELETE, or POST with an idempotency key) and only for network errors, timeouts, 429 and 5xx responses.
- Use exponential backoff with jitter and a small maximum number of attempts; honour the `Retry-After` header when present.
```ts
export class HttpError extends Error {
constructor(public readonly status: number, public readonly url: string, public readonly body: unknown) {
super(`HTTP ${status} for ${url}`);
this.name = 'HttpError';
}
}
const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export async function requestJson<T>(
url: string,
init: RequestInit & { timeoutMs?: number; retries?: number } = {}
): Promise<T> {
const method = (init.method ?? 'GET').toUpperCase();
const idempotent = ['GET', 'HEAD', 'PUT', 'DELETE'].includes(method);
const maxAttempts = idempotent ? 1 + (init.retries ?? 2) : 1;
for (let attempt = 1; ; attempt++) {
try {
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(init.timeoutMs ?? 10_000) });
if (res.ok) return (await res.json()) as T;
const body = await res.json().catch(() => null);
if (attempt < maxAttempts && RETRYABLE.has(res.status)) {
const retryAfter = Number(res.headers.get('retry-after'));
await sleep(Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : backoff(attempt));
continue;
}
throw new HttpError(res.status, url, body);
} catch (err) {
if (err instanceof HttpError || attempt >= maxAttempts) throw err;
await sleep(backoff(attempt)); // network error or timeout
}
}
}
function backoff(attempt: number): number {
return Math.min(8_000, 250 * 2 ** (attempt - 1)) * (0.5 + Math.random() / 2);
}
```
(Callers validate the returned data with a schema when the API is external.)
## Logging
- Log method, URL path, status, duration and attempt number. Never log authorization headers, tokens, cookies or full request bodies with personal data.
## Caching
- Respect HTTP caching headers; for client-side data use a data library (TanStack Query, SWR) with explicit stale times; invalidate after mutations.
## Testing
- Mock the network with MSW (or a local test server) and test success, 4xx, retryable 5xx/429, and timeout paths.
## Documentation
- Document each client function's endpoint, parameters, return type, thrown errors and retry behaviour.
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.
Windsurf
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Windsurf project needs a client for a third-party orders API that sometimes returns 503 and occasionally hangs; the existing code retries POSTs and logs the Authorization header.
Generate src/lib/orders-client.ts with getOrder(id) and createOrder(input) using the API integration rule.
A requestJson-style wrapper with AbortSignal.timeout, retries with jittered backoff only for GET (createOrder not retried unless an Idempotency-Key header is sent), Retry-After support, an HttpError with status and body, schema validation of responses, redacted logging, and MSW tests for 503-then-200, 400 and timeout.
Windsurf's rules documentation (docs.windsurf.com/windsurf/cascade/memories) now redirects to Devin documentation, which describes rules for the Devin Local agent in Devin Desktop. Current rules live in .devin/rules/*.md with a trigger setting, and the legacy Windsurf files (.windsurf/rules/*.md, .windsurf/global_rules.md and .windsurfrules) are still imported by default. AGENTS.md files are read as always-on rules.
.devin/rules/windsurf-api-integration-patterns.mdStarting point, not a tested configuration for your repository. Applied when files matching globs are involved (trigger: glob). Review the instructions, adapt the file paths and run your project's existing checks.
---
trigger: glob
globs: "**/*"
---
When generating code that calls HTTP APIs:
## Typed fetch wrapper
- Wrap `fetch` in one module that sets the base URL, headers and auth, parses JSON, and returns typed data. Validate responses from external APIs with a schema before trusting the type.
## Errors
- Throw (or return) a dedicated error type that carries `status`, the request method/URL and a parsed error body, so callers can branch on status codes. Treat non-2xx responses as errors; `fetch` itself only rejects on network failure.
## Timeouts
- Give every request a timeout with `AbortSignal.timeout(ms)` (combine with a caller's signal using `AbortSignal.any([...])`). Distinguish timeouts (`TimeoutError`) from caller cancellations (`AbortError`).
## Retries
- Retry only idempotent requests (GET, HEAD, PUT, DELETE, or POST with an idempotency key) and only for network errors, timeouts, 429 and 5xx responses.
- Use exponential backoff with jitter and a small maximum number of attempts; honour the `Retry-After` header when present.
```ts
export class HttpError extends Error {
constructor(public readonly status: number, public readonly url: string, public readonly body: unknown) {
super(`HTTP ${status} for ${url}`);
this.name = 'HttpError';
}
}
const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export async function requestJson<T>(
url: string,
init: RequestInit & { timeoutMs?: number; retries?: number } = {}
): Promise<T> {
const method = (init.method ?? 'GET').toUpperCase();
const idempotent = ['GET', 'HEAD', 'PUT', 'DELETE'].includes(method);
const maxAttempts = idempotent ? 1 + (init.retries ?? 2) : 1;
for (let attempt = 1; ; attempt++) {
try {
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(init.timeoutMs ?? 10_000) });
if (res.ok) return (await res.json()) as T;
const body = await res.json().catch(() => null);
if (attempt < maxAttempts && RETRYABLE.has(res.status)) {
const retryAfter = Number(res.headers.get('retry-after'));
await sleep(Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : backoff(attempt));
continue;
}
throw new HttpError(res.status, url, body);
} catch (err) {
if (err instanceof HttpError || attempt >= maxAttempts) throw err;
await sleep(backoff(attempt)); // network error or timeout
}
}
}
function backoff(attempt: number): number {
return Math.min(8_000, 250 * 2 ** (attempt - 1)) * (0.5 + Math.random() / 2);
}
```
(Callers validate the returned data with a schema when the API is external.)
## Logging
- Log method, URL path, status, duration and attempt number. Never log authorization headers, tokens, cookies or full request bodies with personal data.
## Caching
- Respect HTTP caching headers; for client-side data use a data library (TanStack Query, SWR) with explicit stale times; invalidate after mutations.
## Testing
- Mock the network with MSW (or a local test server) and test success, 4xx, retryable 5xx/429, and timeout paths.
## Documentation
- Document each client function's endpoint, parameters, return type, thrown errors and retry behaviour.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
The docs recommend keeping rules short and specific. The current docs say AGENTS.md, AGENTS.local.md and AGENT.md are read as always-on rules, including files in subdirectories. Use .devin/rules/ when you need glob, model-decision or manual triggers.
Documentation checked 2026-11-05: Devin docs: Local customizations (redirect target of Windsurf memories docs)Windsurf docs: Cascade memories (redirects)
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.