implementing-api-patterns
API design and implementation across REST, GraphQL, gRPC, and tRPC patterns. Use when building backend services, public APIs, or service-to-service communication. Covers REST frameworks (FastAPI, Axum, Gin, Hono), GraphQL libraries (Strawberry, async-graphql, gqlgen, Pothos), gRPC (Tonic, Connect-Go), tRPC for TypeScript, pagination strategies (cursor-based, offset-based), rate limiting, caching, versioning, and OpenAPI documentation generation. Includes frontend integration patterns for forms, tables, dashboards, and ai-chat skills.
What this skill does
# API Patterns Skill
## Purpose
Design and implement APIs using the optimal pattern and framework for the use case. Choose between REST, GraphQL, gRPC, and tRPC based on API consumers, performance requirements, and type safety needs.
## When to Use This Skill
Use when:
- Building backend APIs for web, mobile, or service consumers
- Connecting frontend components (forms, tables, dashboards) to databases
- Implementing pagination, rate limiting, or caching strategies
- Generating OpenAPI documentation automatically
- Choosing between REST, GraphQL, gRPC, or tRPC patterns
- Integrating authentication and authorization
- Optimizing API performance and scalability
## Quick Decision Framework
```
WHO CONSUMES YOUR API?
├─ PUBLIC/THIRD-PARTY DEVELOPERS → REST with OpenAPI
│ ├─ Python → FastAPI (auto-docs, 40k req/s)
│ ├─ TypeScript → Hono (edge-first, 50k req/s, 14KB)
│ ├─ Rust → Axum (140k req/s, <1ms latency)
│ └─ Go → Gin (100k+ req/s, mature ecosystem)
│
├─ FRONTEND TEAM (same org)
│ ├─ TypeScript full-stack? → tRPC (E2E type safety)
│ └─ Complex data needs? → GraphQL
│ ├─ Python → Strawberry
│ ├─ Rust → async-graphql
│ ├─ Go → gqlgen
│ └─ TypeScript → Pothos
│
├─ SERVICE-TO-SERVICE (microservices)
│ └─ High performance → gRPC
│ ├─ Rust → Tonic
│ ├─ Go → Connect-Go (browser-friendly)
│ └─ Python → grpcio
│
└─ MOBILE APPS
├─ Bandwidth constrained → GraphQL (request only needed fields)
└─ Simple CRUD → REST (standard, well-understood)
```
## REST Framework Selection
### Python: FastAPI (Recommended)
**Key Features:** Auto OpenAPI docs, Pydantic v2 validation, async/await, 40k req/s
**Basic Example:**
```python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items")
async def create_item(item: Item):
return {"id": 1, **item.dict()}
```
See `references/rest-design-principles.md` for FastAPI patterns and `examples/python-fastapi/`.
### TypeScript: Hono (Edge-First)
**Key Features:** 14KB bundle, runs on any runtime (Node/Deno/Bun/edge), Zod validation, 50k req/s
**Basic Example:**
```typescript
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const app = new Hono()
app.post('/items', zValidator('json', z.object({
name: z.string(), price: z.number()
})), (c) => c.json({ id: 1, ...c.req.valid('json') }))
```
See `references/rest-design-principles.md` for Hono patterns and `examples/typescript-hono/`.
### TypeScript: tRPC (Full-Stack Type Safety)
**Key Features:** Zero codegen, E2E type safety, React Query integration, WebSocket subscriptions
**Basic Example:**
```typescript
import { initTRPC } from '@trpc/server'
import { z } from 'zod'
const t = initTRPC.create()
export const appRouter = t.router({
createItem: t.procedure
.input(z.object({ name: z.string(), price: z.number() }))
.mutation(({ input }) => ({ id: '1', ...input }))
})
export type AppRouter = typeof appRouter
```
See `references/trpc-setup-guide.md` for setup patterns and `examples/typescript-trpc/`.
### Rust: Axum (High Performance)
**Key Features:** Tower middleware, type-safe extractors, 140k req/s, compile-time verification
**Basic Example:**
```rust
use axum::{routing::post, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct CreateItem { name: String, price: f64 }
#[derive(Serialize)]
struct Item { id: u64, name: String, price: f64 }
async fn create_item(Json(payload): Json<CreateItem>) -> Json<Item> {
Json(Item { id: 1, name: payload.name, price: payload.price })
}
```
See `references/rest-design-principles.md` for Axum patterns and `examples/rust-axum/`.
### Go: Gin (Mature Ecosystem)
**Key Features:** Largest Go ecosystem, 100k+ req/s, struct tag validation
**Basic Example:**
```go
type Item struct {
Name string `json:"name" binding:"required"`
Price float64 `json:"price" binding:"required,gt=0"`
}
r := gin.Default()
r.POST("/items", func(c *gin.Context) {
var item Item
if c.ShouldBindJSON(&item); err != nil {
c.JSON(400, gin.H{"error": err.Error()}); return
}
c.JSON(201, item)
})
```
See `references/rest-design-principles.md` for Gin patterns and `examples/go-gin/`.
## Performance Benchmarks
| Language | Framework | Req/s | Latency | Cold Start | Memory | Best For |
|----------|-----------|-------|---------|------------|--------|----------|
| Rust | Actix-web | ~150k | <1ms | N/A | 2-5MB | Maximum throughput |
| Rust | Axum | ~140k | <1ms | N/A | 2-5MB | Ergonomics + performance |
| Go | Gin | ~100k+ | 1-2ms | N/A | 5-10MB | Mature ecosystem |
| TypeScript | Hono | ~50k | <5ms | <5ms | 128MB | Edge deployment |
| Python | FastAPI | ~40k | 5-10ms | 1-2s | 30-50MB | Developer experience |
| TypeScript | Express | ~15k | 10-20ms | 1-3s | 50-100MB | Legacy systems |
**Notes:**
- Benchmarks assume single-core, JSON responses
- Actual performance varies with workload complexity
- Cold start only applies to serverless/edge deployments
## Pagination Strategies
### Cursor-Based (Recommended)
**Advantages:** Handles real-time changes, no skipped/duplicate records, scales to billions
**FastAPI Example:**
```python
@app.get("/items")
async def list_items(cursor: Optional[str] = None, limit: int = 20):
query = db.query(Item).filter(Item.id > cursor) if cursor else db.query(Item)
items = query.limit(limit).all()
return {
"items": items,
"next_cursor": items[-1].id if items else None,
"has_more": len(items) == limit
}
```
### Offset-Based (Simple Cases Only)
Use only for static datasets (<10k records) with direct page access needs.
See `references/pagination-patterns.md` for complete patterns and frontend integration.
## OpenAPI Documentation
| Framework | OpenAPI Support | Docs UI | Configuration |
|-----------|----------------|---------|---------------|
| FastAPI | Automatic | Swagger UI + ReDoc | Built-in |
| Hono | Middleware plugin | Swagger UI | `@hono/swagger-ui` |
| Axum | utoipa crate | Swagger UI | Manual annotations |
| Gin | swaggo/swag | Swagger UI | Comment annotations |
**FastAPI Example (Zero Config):**
```python
app = FastAPI(title="My API", version="1.0.0")
@app.post("/items", tags=["items"])
async def create_item(item: Item) -> Item:
"""Create item with name and price"""
return item
# Docs at /docs, /redoc, /openapi.json
```
See `references/openapi-documentation.md` for framework-specific setup.
Use `scripts/generate_openapi.py` to extract specs programmatically.
## Frontend Integration Patterns
### Forms → REST POST/PUT
**Backend:**
```python
class UserCreate(BaseModel):
email: EmailStr; name: str; age: int
@app.post("/api/users", status_code=201)
async def create_user(user: UserCreate):
return {"id": 1, **user.dict()}
```
**Frontend:**
```typescript
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
if (!res.ok) throw new Error((await res.json()).detail)
```
### Tables → GET with Pagination
See cursor pagination example above and `references/pagination-patterns.md`.
### AI Chat → SSE Streaming
**Backend:**
```python
from sse_starlette.sse import EventSourceResponse
@app.post("/api/chat")
async def chat(message: str):
async def gen():
for chunk in llm_stream(message):
yield {"event": "message", "data": chunk}
return EventSourceResponse(gen())
```
**Frontend:**
```typescript
const es = new EventSource('/api/chat')
es.addEventListener('message', (e) => appendToChat(e.data))
```
See `examples/` for complete integration examples with each frontend skill.
## Rate Limiting
**FastAPI Example (Token Bucket):**
```python
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
@app.get("/itemRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.