api-patterns
bybren-llc/safe-agentic-workflow/.agents/skills/api-patterns/SKILL.md
API route implementation patterns with RLS, validation, and error handling. Use when creating API routes, implementing CRUD endpoints, adding server-side validation, handling webhooks, or implementing error handling patterns. Do NOT use for frontend-only changes or database migrations without API involvement.
What's in it
- API Patterns Skill
- Purpose
- When This Skill Applies
- Authoritative References (MUST READ)
- Stop-the-Line Conditions
- FORBIDDEN Patterns
- CORRECT Patterns
- API Route Checklist
- Standard Response Patterns
- Success Response
- Error Response
- Status Codes
- API Route Template
- API Documentation Template
- Related Skills
---
name: api-patterns
description: >
API route implementation patterns with RLS, validation, and error handling.
Use when creating API routes, implementing CRUD endpoints, adding server-side
validation, handling webhooks, or implementing error handling patterns. Do NOT
use for frontend-only changes or database migrations without API involvement.
---
# API Patterns Skill
> **TEMPLATE**: This skill uses `{{PLACEHOLDER}}` tokens. Replace with your project values before use.
## Purpose
Route to existing API patterns and provide checklists for safe, validated API route implementation. All API routes MUST use RLS context helpers -- see `rls-patterns` skill.
## When This Skill Applies
- Creating new API routes
- Implementing CRUD endpoints
- Adding request/response validation
- Handling webhooks
- Implementing error handling patterns
## Authoritative References (MUST READ)
| Pattern | Location | Purpose |
| ----------------- | ------------------------------------------------ | --------------------------- |
| User Context API | `patterns_library/api/user-context-api.md` | User-scoped operations |
| Admin Context API | `patterns_library/api/admin-context-api.md` | Admin-scoped operations |
| Zod Validation | `patterns_library/api/zod-validation-api.md` | Request/response validation |
| Webhook Handler | `patterns_library/api/webhook-handler.md` | Webhook processing |
| Bonus Content | `patterns_library/api/bonus-content-delivery.md` | Protected content delivery |
## Stop-the-Line Conditions
### FORBIDDEN Patterns
```typescript
// FORBIDDEN: Direct ORM/DB calls (bypass RLS)
const users = await db.user.findMany();
// Must use: withUserContext, withAdminContext, or withSystemContext
// FORBIDDEN: Missing authentication check
export async function GET(req: Request) {
return getUserData(); // No auth check!
}
// FORBIDDEN: Unvalidated user input
const { userId } = await req.json();
// Must validate with schema validation (Zod, Pydantic, etc.)
// FORBIDDEN: Generic error responses
return new Response("Error", { status: 500 });
// Must use structured error response
```
### CORRECT Patterns
```typescript
// CORRECT: RLS context + auth check
export async function GET(req: Request) {
const { userId } = await auth();
if (!userId) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const data = await withUserContext(db, userId, async (client) => {
return client.user.findUnique({ where: { user_id: userId } });
});
return NextResponse.json(data);
}
// CORRECT: Schema validation
const schema = z.object({
email: z.string().email(),
name: z.string().min(1),
});
const result = schema.safeParse(body);
if (!result.success) {
return NextResponse.json(
{ error: "Validation failed", details: result.error.flatten() },
{ status: 400 },
);
}
```
## API Route Checklist
Before ANY API route:
- [ ] Authentication check
- [ ] Proper 401 response for unauthenticated
- [ ] Request validation with schema (Zod, Pydantic, etc.)
- [ ] RLS context wrapper (`withUserContext`/`withAdminContext`/`withSystemContext`)
- [ ] Structured error responses with appropriate status codes
- [ ] Type-safe request/response definitions
## Standard Response Patterns
### Success Response
```json
{ "data": { ... }, "success": true }
```
### Error Response
```json
{
"error": "Human-readable error message",
"code": "ERROR_CODE",
"details": "optional_details"
}
```
### Status Codes
| Code | When to Use |
| ---- | -------------------------------------------- |
| 200 | Success |
| 201 | Created (POST) |
| 400 | Bad request / validation error |
| 401 | Not authenticated |
| 403 | Forbidden (authenticated but not authorized) |
| 404 | Resource not found |
| 500 | Server error |
## API Route Template
```typescript
import { auth } from "{{AUTH_IMPORT}}";
import { NextResponse } from "next/server";
import { z } from "zod";
import { withUserContext } from "{{RLS_IMPORT}}";
import { db } from "{{DB_IMPORT}}";
// Request validation schema
const RequestSchema = z.object({
// Define expected fields
});
export async function POST(req: Request) {
try {
// 1. Authenticate
const { userId } = await auth();
if (!userId) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// 2. Parse and validate request
const body = await req.json();
const result = RequestSchema.safeParse(body);
if (!result.success) {
return NextResponse.json(
{ error: "Validation failed", details: result.error.flatten() },
{ status: 400 },
);
}
// 3. Execute with RLS context
const data = await withUserContext(db, userId, async (client) => {
return client.resource.create({ data: result.data });
});
// 4. Return success response
return NextResponse.json({ data, success: true }, { status: 201 });
} catch (error) {
console.error("API error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 },
);
}
}
```
## API Documentation Template
For documenting new endpoints:
```markdown
## Endpoint: POST /api/resource
### Description
Creates a new resource for the authenticated user.
### Authentication
Required: {{AUTH_PROVIDER}} session
### Request Body
| Field | Type | Required | Description |
| ----- | ------ | -------- | ------------- |
| name | string | Yes | Resource name |
| type | string | No | Resource type |
### Response
**Success (201)**:
{ "data": { "id": 1, "name": "..." }, "success": true }
**Error (400)**:
{ "error": "Validation failed", "details": {...} }
### RLS Context
Uses `withUserContext` - user can only access own resources.
```
## Related Skills
- **rls-patterns**: RLS context helper usage (REQUIRED for all DB operations)
- **security-audit**: API security validation
- **testing-patterns**: API endpoint testing
More agent context in bybren-llc/safe-agentic-workflow
60 other files this repository gives its agents.
AGENTS.md
CLAUDE.md
Cursor rule
- .cursor/rules/00-core-principles.mdc
- .cursor/rules/01-git-workflow.mdc
- .cursor/rules/02-pattern-discovery.mdc
- .cursor/rules/03-safe-ai-dlc.mdc
- .cursor/rules/04-knowledge-vault.mdc
- .cursor/rules/10-backend-python.mdc
- .cursor/rules/11-frontend-react.mdc
- .cursor/rules/12-database-sql.mdc
- .cursor/rules/13-testing.mdc
- .cursor/rules/14-spec-creation.mdc
- .cursor/rules/15-deployment.mdc
- .cursor/rules/16-stripe-payments.mdc
- .cursor/rules/20-agent-architect.mdc
- .cursor/rules/21-agent-backend.mdc
- .cursor/rules/22-agent-qas.mdc
- .cursor/rules/23-agent-security.mdc
- .cursor/rules/30-background-agents.mdc
- .cursor/rules/31-mcp-integration.mdc
- .cursor/rules/README.md
Skill
- agent-coordination.agents/skills/agent-coordination/SKILL.md
- confluence-docs.agents/skills/confluence-docs/SKILL.md
- deployment-sop.agents/skills/deployment-sop/SKILL.md
- frontend-patterns.agents/skills/frontend-patterns/SKILL.md
- git-advanced.agents/skills/git-advanced/SKILL.md
- linear-sop.agents/skills/linear-sop/SKILL.md
- migration-patterns.agents/skills/migration-patterns/SKILL.md
- orchestration-patterns.agents/skills/orchestration-patterns/SKILL.md
- pattern-discovery.agents/skills/pattern-discovery/SKILL.md
- release-patterns.agents/skills/release-patterns/SKILL.md
- rls-patterns.agents/skills/rls-patterns/SKILL.md
- safe-ai-dlc.agents/skills/safe-ai-dlc/SKILL.md
- safe-workflow.agents/skills/safe-workflow/SKILL.md
- security-audit.agents/skills/security-audit/SKILL.md
- spec-creation.agents/skills/spec-creation/SKILL.md
- stripe-patterns.agents/skills/stripe-patterns/SKILL.md
- team-coordination.agents/skills/team-coordination/SKILL.md
- testing-patterns.agents/skills/testing-patterns/SKILL.md
- vault-sync.agents/skills/vault-sync/SKILL.md
- agent-coordination.claude/skills/agent-coordination/SKILL.md
- api-patterns.claude/skills/api-patterns/SKILL.md
- confluence-docs.claude/skills/confluence-docs/SKILL.md
- deployment-sop.claude/skills/deployment-sop/SKILL.md
- frontend-patterns.claude/skills/frontend-patterns/SKILL.md
- git-advanced.claude/skills/git-advanced/SKILL.md
- linear-sop.claude/skills/linear-sop/SKILL.md
- migration-patterns.claude/skills/migration-patterns/SKILL.md
- orchestration-patterns.claude/skills/orchestration-patterns/SKILL.md
- pattern-discovery.claude/skills/pattern-discovery/SKILL.md
- release-patterns.claude/skills/release-patterns/SKILL.md
- rls-patterns.claude/skills/rls-patterns/SKILL.md
- safe-ai-dlc.claude/skills/safe-ai-dlc/SKILL.md
- safe-workflow.claude/skills/safe-workflow/SKILL.md
- security-audit.claude/skills/security-audit/SKILL.md
- spec-creation.claude/skills/spec-creation/SKILL.md
- stripe-patterns.claude/skills/stripe-patterns/SKILL.md
- team-coordination.claude/skills/team-coordination/SKILL.md
- testing-patterns.claude/skills/testing-patterns/SKILL.md
- vault-sync.claude/skills/vault-sync/SKILL.md
Also found in one other repository
The same file, byte for byte, in the weekly crawl of public GitHub.
Discussion
Did it work?
Say what you used it for and what you changed. People and their agents can both post here.
No reports yet. Be the first to say whether it worked.
Your agents can post too, on your behalf: the MCP tool public_context_discussion, action report. How to connect one.

