implementing-api-patterns
This skill provides a decision framework and implementation patterns for designing APIs across REST, GraphQL, gRPC, and tRPC architectures. Use it when building backend services, public APIs, or service-to-service communication to select the optimal framework (FastAPI, Hono, Axum, Gin for REST; Strawberry, async-graphql, Pothos for GraphQL; Tonic, Connect-Go for gRPC) and implement pagination, rate limiting, caching, versioning, and authentication strategies appropriate to your API consumers and performance requirements.
git clone --depth 1 https://github.com/ancoleman/ai-design-components /tmp/implementing-api-patterns && cp -r /tmp/implementing-api-patterns/skills/implementing-api-patterns ~/.claude/skills/implementing-api-patternsSKILL.md
# 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 | SManage Linux systems covering systemd services, process management, filesystems, networking, performance tuning, and troubleshooting. Use when deploying applications, optimizing server performance, diagnosing production issues, or managing users and security on Linux servers.
Data pipelines, feature stores, and embedding generation for AI/ML systems. Use when building RAG pipelines, ML feature serving, or data transformations. Covers feature stores (Feast, Tecton), embedding pipelines, chunking strategies, orchestration (Dagster, Prefect, Airflow), dbt transformations, data versioning (LakeFS), and experiment tracking (MLflow, W&B).
Strategic guidance for designing modern data platforms, covering storage paradigms (data lake, warehouse, lakehouse), modeling approaches (dimensional, normalized, data vault, wide tables), data mesh principles, and medallion architecture patterns. Use when architecting data platforms, choosing between centralized vs decentralized patterns, selecting table formats (Iceberg, Delta Lake), or designing data governance frameworks.
Design cloud network architectures with VPC patterns, subnet strategies, zero trust principles, and hybrid connectivity. Use when planning VPC topology, implementing multi-cloud networking, or establishing secure network segmentation for cloud workloads.
Design comprehensive security architectures using defense-in-depth, zero trust principles, threat modeling (STRIDE, PASTA), and control frameworks (NIST CSF, CIS Controls, ISO 27001). Use when designing security for new systems, auditing existing architectures, or establishing security governance programs.
Assembles component outputs from AI Design Components skills into unified, production-ready component systems with validated token integration, proper import chains, and framework-specific scaffolding. Use as the capstone skill after running theming, layout, dashboard, data-viz, or feedback skills to wire components into working React/Next.js, Python, or Rust projects.
Builds AI chat interfaces and conversational UI with streaming responses, context management, and multi-modal support. Use when creating ChatGPT-style interfaces, AI assistants, code copilots, or conversational agents. Handles streaming text, token limits, regeneration, feedback loops, tool usage visualization, and AI-specific error patterns. Provides battle-tested components from leading AI products with accessibility and performance built in.
Constructs secure, efficient CI/CD pipelines with supply chain security (SLSA), monorepo optimization, caching strategies, and parallelization patterns for GitHub Actions, GitLab CI, and Argo Workflows. Use when setting up automated testing, building, or deployment workflows.