83 lines
2.5 KiB
Markdown
83 lines
2.5 KiB
Markdown
---
|
|
name: api-design-principles
|
|
description: Apply REST API design best practices when designing, reviewing, or building HTTP APIs. Covers naming, versioning, error handling, pagination, auth, and documentation.
|
|
---
|
|
|
|
# API Design Principles Skill
|
|
|
|
Use when: designing a new API, reviewing an existing one, or writing API documentation.
|
|
|
|
## URL & Resource Naming
|
|
- Resources are **nouns**, never verbs: `/users` not `/getUsers`
|
|
- Plural for collections: `/orders`, `/products`
|
|
- Nested for ownership: `/users/{id}/orders`
|
|
- Max 2 levels of nesting before using query params
|
|
- kebab-case for multi-word: `/user-profiles`
|
|
|
|
## HTTP Methods
|
|
| Method | Use | Idempotent |
|
|
|--------|-----|-----------|
|
|
| GET | Read | Yes |
|
|
| POST | Create | No |
|
|
| PUT | Replace (full) | Yes |
|
|
| PATCH | Update (partial) | No |
|
|
| DELETE | Delete | Yes |
|
|
|
|
## Status Codes
|
|
- 200 OK — success with body
|
|
- 201 Created — POST that made something (include Location header)
|
|
- 204 No Content — success, no body (DELETE)
|
|
- 400 Bad Request — client error, invalid input
|
|
- 401 Unauthorized — not authenticated
|
|
- 403 Forbidden — authenticated but not allowed
|
|
- 404 Not Found — resource doesn't exist
|
|
- 409 Conflict — state conflict (duplicate, version mismatch)
|
|
- 422 Unprocessable — valid JSON but fails validation
|
|
- 429 Too Many Requests — rate limited
|
|
- 500 Internal Server Error — server fault
|
|
|
|
## Error Response Format
|
|
```json
|
|
{
|
|
"error": {
|
|
"code": "VALIDATION_FAILED",
|
|
"message": "Human-readable explanation",
|
|
"details": [
|
|
{ "field": "email", "message": "Must be a valid email" }
|
|
]
|
|
}
|
|
}
|
|
```
|
|
|
|
## Pagination
|
|
Use cursor-based for large datasets, offset for small:
|
|
```json
|
|
{
|
|
"data": [...],
|
|
"pagination": {
|
|
"cursor": "abc123",
|
|
"hasMore": true,
|
|
"total": 1042
|
|
}
|
|
}
|
|
```
|
|
|
|
## Versioning
|
|
- URL path versioning: `/v1/users` (most visible, easiest to test)
|
|
- Header versioning for internal APIs: `API-Version: 2024-01-01`
|
|
- Never break v1 — deprecate with sunset dates
|
|
|
|
## Auth
|
|
- Use Bearer tokens: `Authorization: Bearer <token>`
|
|
- API keys for server-to-server
|
|
- OAuth 2.1 + PKCE for user-facing
|
|
- Always HTTPS — no exceptions
|
|
|
|
## Design Checklist
|
|
- [ ] Resources are nouns, actions are HTTP methods
|
|
- [ ] Consistent naming throughout (pick one style, stick to it)
|
|
- [ ] All errors have machine-readable codes
|
|
- [ ] Breaking changes increment version
|
|
- [ ] Endpoints are documented (OpenAPI/Swagger preferred)
|
|
- [ ] Rate limits documented and returning 429 with Retry-After header
|
|
- [ ] Idempotency keys on POST for critical operations
|