Comprehensive guide for designing RESTful APIs including resource modeling, versioning strategies, HATEOAS, pagination, filtering, and HTTP best practices
Comprehensive guide for designing, implementing, and maintaining world-class RESTful APIs
This skill provides a complete framework for building RESTful APIs following industry best practices. Whether you're designing a new API from scratch or refactoring an existing one, this guide covers everything from resource modeling to performance optimization.
/api/v1/users) - Most commonX-API-Version: 2.0) - Clean URIsAccept: application/vnd.api.v2+json) - RESTful/users?version=2) - Simple but limitedResource Design:
✓ Use plural nouns for collections (/users, /products)
✓ Use lowercase with hyphens (/user-profiles)
✓ Keep nesting to 2-3 levels maximum
✓ Use query parameters for filtering/sorting
✓ Implement proper pagination
HTTP Methods:
✓ GET for retrieval (safe, idempotent, cacheable)
✓ POST for creation (not idempotent)
✓ PUT for full replacement (idempotent)
✓ PATCH for partial updates (idempotent)
✓ DELETE for removal (idempotent)
Status Codes:
✓ 200 OK for successful GET/PUT/PATCH
✓ 201 Created for successful POST
✓ 204 No Content for successful DELETE
✓ 400 Bad Request for client errors
✓ 401 Unauthorized for authentication required
✓ 403 Forbidden for authorization failures
✓ 404 Not Found for missing resources
✓ 422 Unprocessable Entity for validation errors
✓ 429 Too Many Requests for rate limiting
✓ 500 Internal Server Error for server issues
Versioning:
✓ Choose one strategy and stick to it
✓ Document version lifecycle
✓ Support multiple versions temporarily
✓ Deprecate gracefully with warnings
✓ Sunset old versions with notice
Security:
✓ Always use HTTPS in production
✓ Implement authentication
✓ Validate all inputs
✓ Sanitize all outputs
✓ Use rate limiting
✓ Enable CORS carefully
✓ Log security events
Performance:
✓ Implement caching (ETags, Cache-Control)
✓ Use compression for large responses
✓ Paginate collections
✓ Optimize database queries
✓ Use async I/O
✓ Monitor performance metrics
Documentation:
✓ Generate OpenAPI specs
✓ Provide interactive docs
✓ Include code examples
✓ Document error responses
✓ Keep changelog updated
GET - Retrieval
Use when: Fetching data without side effects
Examples:
- List all users: GET /users
- Get user by ID: GET /users/123
- Search products: GET /products?q=laptop
Safe: Yes | Idempotent: Yes | Cacheable: Yes
POST - Creation or Actions
Use when: Creating new resources or triggering actions
Examples:
- Create user: POST /users
- Login: POST /auth/login
- Process payment: POST /payments/123/process
Safe: No | Idempotent: No | Cacheable: No
PUT - Full Replacement
Use when: Replacing entire resource
Examples:
- Update all user fields: PUT /users/123
- Replace configuration: PUT /settings
Requires: All fields in request body
Safe: No | Idempotent: Yes | Cacheable: No
PATCH - Partial Update
Use when: Updating specific fields
Examples:
- Update email only: PATCH /users/123 {"email": "new@example.com"}
- Change status: PATCH /orders/456 {"status": "shipped"}
Requires: Only fields to update
Safe: No | Idempotent: Yes | Cacheable: No
DELETE - Removal
Use when: Removing resources
Examples:
- Delete user: DELETE /users/123
- Cancel subscription: DELETE /subscriptions/789
Safe: No | Idempotent: Yes | Cacheable: No
Use Nested Routes When:
GET /posts/42/commentsUse Flat Routes When:
GET /comments?post_id=42&user_id=5Hybrid Approach:
# Create comment on post (nested)
POST /posts/42/comments
# Get comments across all posts (flat)
GET /comments?user_id=5
# Get specific comment (flat - if you have ID)
GET /comments/123
Choose URI Versioning if:
/api/v1/users, /api/v2/usersChoose Header Versioning if:
X-API-Version: 2.0Choose Content Negotiation if:
Accept: application/vnd.api.v2+jsonOffset-Based (Traditional)
Best for: Small to medium datasets, user-facing pages
Pros: Simple, supports jumping to any page
Cons: Performance issues with large offsets, inconsistent with data changes
Example: GET /items?limit=10&offset=20
Cursor-Based (Recommended)
Best for: Large datasets, real-time data, feeds
Pros: Consistent results, efficient, handles data changes
Cons: Can't jump to arbitrary page
Example: GET /items?limit=10&cursor=eyJpZCI6MTIzfQ==
Page-Based
Best for: User interfaces with page numbers
Pros: User-friendly, intuitive
Cons: Same issues as offset-based
Example: GET /items?page=3&page_size=10
Keyset Pagination
Best for: Performance-critical applications
Pros: Best performance, consistent
Cons: Requires indexed column, complex implementation
Example: GET /items?limit=10&since_id=123
Single field:
GET /products?category=electronics
Multiple fields:
GET /products?category=electronics&min_price=100&max_price=500
Multiple values (OR):
GET /products?tags=wireless,bluetooth
Range queries:
GET /events?start_date=2024-01-01&end_date=2024-12-31
Text search:
GET /articles?q=machine+learning
Negation:
GET /users?status!=inactive
Complex queries (JSON):
GET /products?filter={"category": "electronics", "price": {"$gte": 100}}
Single field:
GET /products?sort=price
Descending:
GET /products?sort=-price
Multiple fields:
GET /products?sort=category,price
Mixed order:
GET /products?sort=category,-price
Query parameter style:
GET /products?sort_by=price&order=desc
Bulk create:
POST /users/bulk
Body: [{"name": "User 1"}, {"name": "User 2"}]
Bulk update:
PATCH /users/bulk
Body: [{"id": 1, "status": "active"}, {"id": 2, "status": "inactive"}]
Bulk delete:
DELETE /users?ids=1,2,3,4
Batch processing:
POST /jobs/batch
Body: {"operations": [{"action": "create", "resource": "user", "data": {...}}]}
For operations that don't fit CRUD:
User actions:
POST /users/123/activate
POST /users/123/deactivate
POST /users/123/reset-password
Order actions:
POST /orders/456/cancel
POST /orders/456/refund
POST /orders/456/ship
Document actions:
POST /documents/789/publish
POST /documents/789/archive
POST /documents/789/duplicate
Connection Pooling:
# FastAPI with asyncpg
from databases import Database
database = Database("postgresql://user:pass@localhost/db")
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
JWT with Refresh Tokens:
POST /auth/login
→ Returns: access_token (15 min), refresh_token (7 days)
GET /api/resource
→ Header: Authorization: Bearer {access_token}
POST /auth/refresh
→ Body: {refresh_token}
→ Returns: new access_token
Webhook Patterns:
Register webhook:
POST /webhooks
Body: {"url": "https://example.com/webhook", "events": ["user.created"]}
Webhook delivery:
POST https://example.com/webhook
Headers: X-Webhook-Signature: {hmac_signature}
Body: {"event": "user.created", "data": {...}}
Verify webhooks:
GET /webhooks/{id}
DELETE /webhooks/{id}
This skill is continuously updated with new patterns, examples, and best practices from real-world API development.
Version: 1.0.0 Last Updated: October 2025 Maintained By: Claude Code Skills Team
npx skills add manutej/rest-api-design-patterns下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer
Tags:rest-api, api-design, http, resource-modeling, versioning, best-practices