Skip to main content
ClaudeWave
Skill58 repo starsupdated 2mo ago

api-patterns

Creates API route handlers, implements Server Actions with Zod schema validation, integrates external REST APIs with error handling. Use when adding endpoints, building request handlers, or wiring external services (endpoint, REST API, request handling, fetch, .ts route files).

Install in Claude Code
Copy
git clone --depth 1 https://github.com/monkilabs/opencastle /tmp/api-patterns && cp -r /tmp/api-patterns/src/orchestrator/skills/api-patterns ~/.claude/skills/api-patterns
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# API Patterns

Project-specific config: [api-config.md](../../.opencastle/stack/api-config.md).

## Architecture

| Layer | Use for |
|-------|---------|
| **Server Actions** (preferred) | mutations, form submissions, data writes, auth |
| **Route Handlers** (`route.ts`) | analytics, autocomplete, external integrations |
| **Proxy layer** | IP rate limiting, fingerprinting, bot detection |

## Code Patterns

### Route Handler

```typescript
// app/api/example/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
const schema = z.object({ query: z.string().min(1).max(200) });

export async function GET(request: NextRequest) {
  const result = schema.safeParse(Object.fromEntries(request.nextUrl.searchParams));
  if (!result.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 });
  return NextResponse.json(data);
}

```

### Fetching external APIs — example with retry and error handling

```ts
import fetch from 'node-fetch';
async function fetchWithRetry(url:string, opts={}, retries=2){
  for(let i=0;i<=retries;i++){
    try{ const res = await fetch(url, opts); if(!res.ok) throw new Error(`HTTP ${res.status}`); return await res.json(); }
    catch(e){ if(i===retries) throw e; await new Promise(r=>setTimeout(r, 500*(i+1))); }
  }
}

// usage
const data = await fetchWithRetry('https://api.example.com/data');
```
```

### Server Action

```typescript
'use server';
import { createServerClient } from '@libs/auth';
import { revalidatePath } from 'next/cache';

export async function submitAction(formData: FormData) {
  const { data: { user } } = await (await createServerClient()).auth.getUser();
  if (!user) return { error: 'Unauthorized' };
  revalidatePath('/places');
  return { success: true };
}
```

## Quick Workflow
1. Create route file: `app/api/<name>/route.ts` or `app/<segment>/route.ts`
2. Add Zod schema; validate input at top of handler
3. Implement handler logic with explicit error/response shapes
4. Add unit/integration tests for validation, happy/error paths
5. Verification: run a quick smoke test (example):

```bash
curl -fsS "http://localhost:3000/api/<name>?query=test" || (echo "route failed" && exit 1)
```

## Design Rules

- Server Actions for mutations; Route Handlers for external/public endpoints
- Validate all input with Zod on server
- RESTful nouns: `/api/v1/places/:slug`; HTTP methods: `GET` read, `POST` create, `PATCH` update, `DELETE` remove
- Response envelope: `{ "data": ..., "meta": { "total": 42, "page": 1 } }`
- Error shape: `{ "error": { "code": "VALIDATION_ERROR", "message": "...", "details": [...] } }`
- Status codes: 400, 401, 403, 404, 422, 429, 500 — never leak stack traces
- Pagination: cursor-based preferred; params: `limit`, `cursor`, `sort`, `order`
- Versioning: `/api/v1/...`; add fields only, never remove/rename; deprecation headers before removal
- Rate-limit public endpoints; set `Cache-Control`, `ETag`/`If-None-Match` headers
astro-frameworkSkill

Creates pages/layouts, defines content collections, configures hydration directives, and wires integrations. Use when adding or modifying Astro pages, layouts, components, or content collections. Trigger terms: Astro, content collection, client:load, client:visible, astro:content

browser-testingSkill

Drive real browsers via Chrome DevTools MCP: navigate pages, capture snapshots, run responsive checks, and collect console/perf traces. Use when the user mentions: 'validate UI change in Chrome', 'capture a screenshot', 'run responsive checks', or 'collect console logs'. Trigger terms: browser testing, DevTools, console logs, screenshot, responsive testing

cloudflare-platformSkill

Creates and deploys Cloudflare Workers, configures wrangler.toml bindings, sets up KV/D1/R2 storage and Durable Objects, manages Pages deployments, and implements edge function patterns. Use when building or deploying Cloudflare Workers, setting up Pages, working with KV/D1/R2 storage, configuring wrangler.toml, or deploying edge applications.

contentful-cmsSkill

Creates Contentful content types, queries entries via GraphQL/REST, runs CLI migrations, and manages assets and locales. Use when building or modifying Contentful content models, writing queries, or migrating content.

convex-databaseSkill

Convex reactive database patterns, schema design, real-time queries, mutations, actions, authentication, migrations, performance optimization, and component creation. Use when designing Convex schemas, writing queries/mutations, managing the Convex backend, setting up auth, migrating data, optimizing performance, or building Convex components.

coolify-deploymentSkill

Deploys applications, databases, and services on self-hosted Coolify instances, manages environments and env vars, runs infrastructure diagnostics, and performs batch operations. Use when deploying apps to Coolify, managing Coolify servers, debugging deployment issues, setting up databases, or managing Coolify infrastructure.

cypress-testingSkill

Writes Cypress E2E/component tests, configures `cy.intercept()` and `cy.session()`, authors custom commands, and wires CI artifacts. Use when creating E2E specs, component tests, or CI test pipelines. Trigger terms: cypress, e2e, component test, cy.intercept, cy.session

drizzle-ormSkill

Drizzle ORM schema definition, type-safe queries, relational queries, CRUD operations, transactions, migrations with drizzle-kit, and database setup for PostgreSQL, MySQL, and SQLite. Use when defining database schemas, writing queries or joins, managing migrations, setting up a new Drizzle project, or working with drizzle-kit.