API Patterns Reference
Target Spawn
Backend domain work spawned via Agent(general-purpose) with backend instructions - Applies these patterns directly to API implementation and review.
RESTful API Design Conventions
| Principle |
Convention |
Example |
| Resource Naming |
Plural nouns, lowercase, kebab-case |
/api/v1/user-profiles |
| Collection |
GET returns array with pagination |
GET /users?page=1&limit=20 |
| Single Resource |
GET returns object |
GET /users/{id} |
| Create |
POST to collection |
POST /users |
| Update (full) |
PUT to resource |
PUT /users/{id} |
| Update (partial) |
PATCH to resource |
PATCH /users/{id} |
| Delete |
DELETE to resource |
DELETE /users/{id} |
| Nested Resources |
Max 2 levels deep |
/users/{id}/posts |
| Filtering |
Query params |
?status=active&role=admin |
| Sorting |
Sort param |
?sort=-created_at,name |
| Versioning |
URL prefix |
/api/v1/, /api/v2/ |
HTTP Status Code Guide
| Category |
Code |
When to Use |
| Success |
200 OK |
Successful GET, PUT, PATCH, DELETE |
| Success |
201 Created |
Successful POST (resource created) |
| Success |
204 No Content |
Successful DELETE (no body) |
| Client Error |
400 Bad Request |
Malformed request, validation failure |
| Client Error |
401 Unauthorized |
Missing or invalid authentication |
| Client Error |
403 Forbidden |
Authenticated but not authorized |
| Client Error |
404 Not Found |
Resource does not exist |
| Client Error |
409 Conflict |
Resource state conflict (duplicate) |
| Client Error |
422 Unprocessable |
Valid syntax but semantic error |
| Client Error |
429 Too Many |
Rate limit exceeded |
| Server Error |
500 Internal |
Unexpected server error |
| Server Error |
503 Service Unavailable |
Maintenance or overload |
Error Response Format
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Input validation failed",
"details": [
{"field": "email", "message": "Must be a valid email address"},
{"field": "age", "message": "Must be between 0 and 150"}
],
"request_id": "req_abc123"
}
}
Rules:
- Never expose stack traces or internal details in production
- Always include request_id for traceability
- Use consistent error codes (ENUM, not free text)
- Login failures: "Invalid email or password" (never reveal which)
Pagination Pattern
{
"data": [...],
"pagination": {
"page": 1,
"limit": 20,
"total": 150,
"total_pages": 8,
"has_next": true,
"has_prev": false
}
}
For cursor-based (large datasets):
{
"data": [...],
"cursor": {
"next": "eyJpZCI6MTAwfQ==",
"has_more": true
}
}
Input Validation Checklist
| Validation |
Method |
Tool |
| Type validation |
Schema validation |
Zod, Joi, pydantic, Go validator |
| Length limits |
Min/max constraints |
Schema min/max |
| Pattern matching |
Regex |
Email, URL, phone patterns |
| Range validation |
Number/date bounds |
min/max values |
| Enumeration |
Allowed values |
enum types |
| SQL Injection |
Parameterized queries |
ORM (Prisma, GORM, SQLAlchemy) |
| XSS |
HTML escaping |
Template engines, DOMPurify |
| Path Traversal |
Path normalization |
filepath.Clean + whitelist |
Rate Limiting Strategy
| Target |
Limit |
Key |
| Auth endpoints |
5 req/min |
IP |
| General API |
100 req/min |
User token |
| File upload |
10 req/hour |
User token |
| Public API |
30 req/min |
IP |
Response headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After (on 429).
API Versioning Strategy
| Strategy |
Use Case |
Example |
| URL prefix |
Most APIs |
/api/v1/users |
| Header |
Internal APIs |
Accept: application/vnd.api+json; version=2 |
| Query param |
Simple APIs |
/users?version=2 |
Breaking changes that require version bump:
- Removing or renaming fields
- Changing field types
- Removing endpoints
- Changing authentication methods
Non-breaking changes (no version bump needed):
- Adding new optional fields
- Adding new endpoints
- Adding new query parameters
Common Rationalizations
| Rationalization |
Reality |
| "REST naming conventions are just aesthetics" |
Consistent resource naming is how clients discover and predict endpoints. Inconsistency multiplies documentation burden. |
| "GraphQL solves over-fetching, so I do not need to design response shapes" |
GraphQL shifts complexity to the resolver layer. Poorly designed schemas create N+1 queries and authorization gaps. |
| "Error codes are internal details, clients just need the message" |
Clients need machine-readable error codes for programmatic handling. Messages are for humans, codes are for code. |
| "PATCH and PUT are interchangeable" |
PATCH applies partial updates; PUT replaces the entire resource. Using them incorrectly breaks idempotency expectations. |
| "I will version the API when it becomes necessary" |
Versioning after breaking changes forces emergency migrations. Plan versioning from the first release. |
Hyrum's Law: Every observable API behavior will eventually be depended on by clients. Undocumented response fields, error formats, and timing characteristics become implicit contracts.
Red Flags
- API returns different error formats across endpoints
- Resource names use verbs instead of nouns (e.g., /getUser instead of /users/:id)
- No pagination on list endpoints that can return unbounded results
- Breaking change deployed without API version bump
- GraphQL schema allows unbounded depth or circular queries without limits
Verification
1---
2name: moai-ref-api-patterns
3description: >
4 REST/GraphQL API design patterns, error handling conventions, and input validation
5 reference for backend development. Agent-extending skill that amplifies backend domain
6 work (spawned via Agent(general-purpose) with backend instructions) with production-grade
7 API patterns. Use when designing APIs, implementing endpoints, or reviewing backend code.
8 NOT for: frontend development, DevOps, database schema design, security audits.
9
10when_to_use: >
11 Use for REST/GraphQL API design patterns: endpoint and route design,
12 handler structure, request/response conventions, error handling, and
13 input validation. Amplifies backend domain work (Agent(general-purpose)
14 with backend instructions) with production-grade API patterns.
15
16user-invocable: false
17metadata:
18 source: https://skillmd.com/skills/modu-ai/moai-ref-api-patterns
19 version: "1.0.0"
20 category: "domain"
21 status: "active"
22 updated: "2026-03-30"
23 tags: "api, rest, graphql, patterns, backend, reference"
24
25# MoAI Extension: Progressive Disclosure
26progressive_disclosure:
27 enabled: true
28 level1_tokens: 100
29 level2_tokens: 3000
30---
31
32# API Patterns Reference
33
34## Target Spawn
35
36Backend domain work spawned via `Agent(general-purpose)` with backend instructions - Applies these patterns directly to API implementation and review.
37
38## RESTful API Design Conventions
39
40| Principle | Convention | Example |
41|-----------|-----------|---------|
42| Resource Naming | Plural nouns, lowercase, kebab-case | `/api/v1/user-profiles` |
43| Collection | GET returns array with pagination | `GET /users?page=1&limit=20` |
44| Single Resource | GET returns object | `GET /users/{id}` |
45| Create | POST to collection | `POST /users` |
46| Update (full) | PUT to resource | `PUT /users/{id}` |
47| Update (partial) | PATCH to resource | `PATCH /users/{id}` |
48| Delete | DELETE to resource | `DELETE /users/{id}` |
49| Nested Resources | Max 2 levels deep | `/users/{id}/posts` |
50| Filtering | Query params | `?status=active&role=admin` |
51| Sorting | Sort param | `?sort=-created_at,name` |
52| Versioning | URL prefix | `/api/v1/`, `/api/v2/` |
53
54## HTTP Status Code Guide
55
56| Category | Code | When to Use |
57|----------|------|-------------|
58| Success | 200 OK | Successful GET, PUT, PATCH, DELETE |
59| Success | 201 Created | Successful POST (resource created) |
60| Success | 204 No Content | Successful DELETE (no body) |
61| Client Error | 400 Bad Request | Malformed request, validation failure |
62| Client Error | 401 Unauthorized | Missing or invalid authentication |
63| Client Error | 403 Forbidden | Authenticated but not authorized |
64| Client Error | 404 Not Found | Resource does not exist |
65| Client Error | 409 Conflict | Resource state conflict (duplicate) |
66| Client Error | 422 Unprocessable | Valid syntax but semantic error |
67| Client Error | 429 Too Many | Rate limit exceeded |
68| Server Error | 500 Internal | Unexpected server error |
69| Server Error | 503 Service Unavailable | Maintenance or overload |
70
71## Error Response Format
72
73```json
74{
75 "error": {
76 "code": "VALIDATION_ERROR",
77 "message": "Input validation failed",
78 "details": [
79 {"field": "email", "message": "Must be a valid email address"},
80 {"field": "age", "message": "Must be between 0 and 150"}
81 ],
82 "request_id": "req_abc123"
83 }
84}
85```
86
87Rules:
88- Never expose stack traces or internal details in production
89- Always include request_id for traceability
90- Use consistent error codes (ENUM, not free text)
91- Login failures: "Invalid email or password" (never reveal which)
92
93## Pagination Pattern
94
95```json
96{
97 "data": [...],
98 "pagination": {
99 "page": 1,
100 "limit": 20,
101 "total": 150,
102 "total_pages": 8,
103 "has_next": true,
104 "has_prev": false
105 }
106}
107```
108
109For cursor-based (large datasets):
110```json
111{
112 "data": [...],
113 "cursor": {
114 "next": "eyJpZCI6MTAwfQ==",
115 "has_more": true
116 }
117}
118```
119
120## Input Validation Checklist
121
122| Validation | Method | Tool |
123|-----------|--------|------|
124| Type validation | Schema validation | Zod, Joi, pydantic, Go validator |
125| Length limits | Min/max constraints | Schema min/max |
126| Pattern matching | Regex | Email, URL, phone patterns |
127| Range validation | Number/date bounds | min/max values |
128| Enumeration | Allowed values | enum types |
129| SQL Injection | Parameterized queries | ORM (Prisma, GORM, SQLAlchemy) |
130| XSS | HTML escaping | Template engines, DOMPurify |
131| Path Traversal | Path normalization | filepath.Clean + whitelist |
132
133## Rate Limiting Strategy
134
135| Target | Limit | Key |
136|--------|-------|-----|
137| Auth endpoints | 5 req/min | IP |
138| General API | 100 req/min | User token |
139| File upload | 10 req/hour | User token |
140| Public API | 30 req/min | IP |
141
142Response headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, `Retry-After` (on 429).
143
144## API Versioning Strategy
145
146| Strategy | Use Case | Example |
147|----------|----------|---------|
148| URL prefix | Most APIs | `/api/v1/users` |
149| Header | Internal APIs | `Accept: application/vnd.api+json; version=2` |
150| Query param | Simple APIs | `/users?version=2` |
151
152Breaking changes that require version bump:
153- Removing or renaming fields
154- Changing field types
155- Removing endpoints
156- Changing authentication methods
157
158Non-breaking changes (no version bump needed):
159- Adding new optional fields
160- Adding new endpoints
161- Adding new query parameters
162
163<!-- moai:evolvable-start id="rationalizations" -->
164## Common Rationalizations
165
166| Rationalization | Reality |
167|---|---|
168| "REST naming conventions are just aesthetics" | Consistent resource naming is how clients discover and predict endpoints. Inconsistency multiplies documentation burden. |
169| "GraphQL solves over-fetching, so I do not need to design response shapes" | GraphQL shifts complexity to the resolver layer. Poorly designed schemas create N+1 queries and authorization gaps. |
170| "Error codes are internal details, clients just need the message" | Clients need machine-readable error codes for programmatic handling. Messages are for humans, codes are for code. |
171| "PATCH and PUT are interchangeable" | PATCH applies partial updates; PUT replaces the entire resource. Using them incorrectly breaks idempotency expectations. |
172| "I will version the API when it becomes necessary" | Versioning after breaking changes forces emergency migrations. Plan versioning from the first release. |
173
174**Hyrum's Law**: Every observable API behavior will eventually be depended on by clients. Undocumented response fields, error formats, and timing characteristics become implicit contracts.
175
176<!-- moai:evolvable-end -->
177
178<!-- moai:evolvable-start id="red-flags" -->
179## Red Flags
180
181- API returns different error formats across endpoints
182- Resource names use verbs instead of nouns (e.g., /getUser instead of /users/:id)
183- No pagination on list endpoints that can return unbounded results
184- Breaking change deployed without API version bump
185- GraphQL schema allows unbounded depth or circular queries without limits
186
187<!-- moai:evolvable-end -->
188
189<!-- moai:evolvable-start id="verification" -->
190## Verification
191
192- [ ] All endpoints follow consistent naming convention (nouns, plurals, nested resources)
193- [ ] Error responses use a standard format with machine-readable error code
194- [ ] List endpoints implement pagination with documented limits
195- [ ] API versioning strategy present and enforced (URL path, header, or query param)
196- [ ] Breaking vs non-breaking change classification documented for recent changes
197- [ ] Input validation returns 400 with specific field-level error details
198
199<!-- moai:evolvable-end -->