api-patterns
REST API best practices including request validation, error handling, authentication, rate limiting, and documentation. Use when building backend APIs.
What this skill does
# API Patterns Skill
## Quick Reference
**Use when**: Building REST APIs, implementing authentication, handling errors, validating inputs
**Key Patterns**:
- Request validation
- Standardized error responses
- Authentication middleware
- Rate limiting
- Pagination
- API documentation
---
## 1. Request Validation
**Always validate incoming requests at the boundary.**
Pattern with schema validation:
```typescript
// Define schema for expected input
const CreateUserSchema = {
email: 'string, email format, required',
password: 'string, min 12 chars, required',
name: 'string, 2-100 chars, required',
age: 'number, integer, min 18, optional'
};
// Validate in route handler
function createUserHandler(req, res) {
const validation = validateSchema(CreateUserSchema, req.body);
if (!validation.success) {
return res.status(400).json({
error: 'Validation failed',
details: validation.errors
});
}
// Proceed with validated data
const user = await createUser(validation.data);
res.status(201).json(user);
}
```
**Key Points**:
- Validate at API boundary, not deep in business logic
- Return specific error messages
- Use 400 status code for validation failures
---
## 2. Standardized Error Responses
**Use consistent error format across all endpoints.**
```typescript
// Error response structure
interface ErrorResponse {
error: string; // Human-readable message
code?: string; // Machine-readable error code
details?: unknown; // Additional context (validation errors, etc.)
}
// Custom error class
class AppError extends Error {
constructor(
message: string,
public statusCode: number = 500,
public code?: string,
public details?: unknown
) {
super(message);
}
}
// Usage
throw new AppError('User not found', 404, 'USER_NOT_FOUND');
throw new AppError('Validation failed', 400, 'VALIDATION_ERROR', errors);
```
**Error Handler Pattern**:
```typescript
function errorHandler(err, req, res, next) {
// Known application errors
if (err instanceof AppError) {
return res.status(err.statusCode).json({
error: err.message,
code: err.code,
details: err.details
});
}
// Log unexpected errors (don't expose to user)
console.error('Unexpected error:', err);
res.status(500).json({
error: 'Internal server error'
});
}
```
---
## 3. Authentication Middleware
**Protect routes with authentication middleware.**
```typescript
// Auth middleware pattern
function requireAuth(req, res, next) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) {
throw new AppError('Authentication required', 401, 'NO_TOKEN');
}
try {
const decoded = verifyToken(token);
req.userId = decoded.userId;
next();
} catch (err) {
throw new AppError('Invalid token', 401, 'INVALID_TOKEN');
}
}
// Optional auth (for routes that work with or without auth)
function optionalAuth(req, res, next) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (token) {
try {
const decoded = verifyToken(token);
req.userId = decoded.userId;
} catch {
// Ignore invalid tokens in optional auth
}
}
next();
}
// Usage
router.get('/api/profile', requireAuth, getProfileHandler);
router.get('/api/posts', optionalAuth, getPostsHandler);
```
---
## 4. Rate Limiting
**Protect endpoints from abuse.**
```typescript
// General rate limit
const generalLimiter = {
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // 100 requests per window
};
// Strict limit for auth endpoints
const authLimiter = {
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // Only 5 attempts
skipSuccessfulRequests: true
};
// Apply to routes
app.use('/api/', rateLimitMiddleware(generalLimiter));
router.post('/api/auth/login', rateLimitMiddleware(authLimiter), loginHandler);
```
---
## 5. Pagination
**Standard pagination for list endpoints.**
```typescript
// Pagination parameters
const DEFAULT_PAGE = 1;
const DEFAULT_LIMIT = 20;
const MAX_LIMIT = 100;
function parsePagination(query) {
const page = Math.max(1, parseInt(query.page) || DEFAULT_PAGE);
const limit = Math.min(MAX_LIMIT, Math.max(1, parseInt(query.limit) || DEFAULT_LIMIT));
const offset = (page - 1) * limit;
return { page, limit, offset };
}
// Response format
function paginatedResponse(data, total, page, limit) {
return {
data,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
hasNext: page < Math.ceil(total / limit),
hasPrev: page > 1
}
};
}
// Usage in handler
async function listUsersHandler(req, res) {
const { page, limit, offset } = parsePagination(req.query);
const [users, total] = await Promise.all([
db.users.findMany({ skip: offset, take: limit }),
db.users.count()
]);
res.json(paginatedResponse(users, total, page, limit));
}
```
---
## 6. API Response Format
**Use consistent response structure.**
```typescript
// Success response
{
data: T, // The requested resource(s)
meta?: {
pagination?: {...}, // For lists
timestamp: string // ISO timestamp
}
}
// Error response
{
error: string, // Human-readable message
code?: string, // Machine-readable code
details?: unknown // Additional context
}
```
---
## 7. HTTP Status Codes
Use appropriate status codes:
| Code | Meaning | When to Use |
|------|---------|-------------|
| 200 | OK | Successful GET, PUT, PATCH |
| 201 | Created | Successful POST (resource created) |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Validation errors, malformed request |
| 401 | Unauthorized | Missing or invalid authentication |
| 403 | Forbidden | Authenticated but not authorized |
| 404 | Not Found | Resource doesn't exist |
| 409 | Conflict | Resource conflict (duplicate, etc.) |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Error | Unexpected server error |
---
## 8. RESTful Resource Naming
Follow conventions:
- `GET /api/resources` - List all (with pagination)
- `GET /api/resources/:id` - Get one
- `POST /api/resources` - Create new
- `PUT /api/resources/:id` - Replace entirely
- `PATCH /api/resources/:id` - Partial update
- `DELETE /api/resources/:id` - Delete
Nested resources:
- `GET /api/users/:userId/posts` - User's posts
- `POST /api/users/:userId/posts` - Create post for user
---
## Checklist for New Endpoints
- [ ] Input validation with schema
- [ ] Authentication check (if protected)
- [ ] Authorization check (if resource-specific)
- [ ] Rate limiting configured
- [ ] Error handling with appropriate codes
- [ ] Consistent response format
- [ ] Pagination for lists
- [ ] Documentation/comments
- [ ] Tests covering success and error cases
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.