Skill 寫法圖鑑

api-design-principles

wshobson | 架構與重構 | 原文 | MIT

REST 和 GraphQL 的 API 設計原則,做出直覺、可擴充、好維護的 API

中文翻譯

---
name: api-design-principles
description: 掌握 REST 和 GraphQL 的 API 設計原則,打造直覺、可擴充、好維護、讓開發者滿意的 API。在設計新 API、審查 API 規格,或建立 API 設計標準時使用。
---

# API 設計原則

掌握 REST 和 GraphQL 的 API 設計原則,打造直覺、可擴充、好維護、讓開發者滿意,而且經得起時間考驗的 API。

## 何時使用這個 Skill

- 設計新的 REST 或 GraphQL API
- 重構既有 API,讓它更好用
- 為你的團隊建立 API 設計標準
- 實作之前審查 API 規格
- 在不同 API 範式之間遷移(REST 到 GraphQL 等)
- 建立對開發者友善的 API 文件
- 針對特定使用情境最佳化 API(行動裝置、第三方整合)

## 核心概念

### 1. RESTful 設計原則

**以資源為導向的架構**

- 資源是名詞(users、orders、products),不是動詞
- 用 HTTP method 表達動作(GET、POST、PUT、PATCH、DELETE)
- URL 代表資源的階層
- 一致的命名慣例

**HTTP Method 的語意:**

- `GET`:取得資源(idempotent、安全)
- `POST`:建立新資源
- `PUT`:取代整個資源(idempotent)
- `PATCH`:部分更新資源
- `DELETE`:移除資源(idempotent)

### 2. GraphQL 設計原則

**Schema 優先的開發**

- 用型別定義你的領域模型
- 用 Query 讀取資料
- 用 Mutation 修改資料
- 用 Subscription 做即時更新

**Query 結構:**

- client 只要求自己需要的東西
- 單一 endpoint,多種操作
- 強型別的 schema
- 內建 introspection

### 3. API 版本策略

**URL 版本:**

```
/api/v1/users
/api/v2/users
```

**Header 版本:**

```
Accept: application/vnd.api+json; version=1
```

**Query Parameter 版本:**

```
/api/users?version=1
```

## 詳細模式與實作範例

詳細的模式文件放在 `references/details.md`。上面的導覽層不夠用時,再讀那個檔案。

## 最佳實務

### REST API

1. **一致的命名**:集合用複數名詞(`/users`,不是 `/user`)
2. **無狀態**:每個請求都包含所有必要的資訊
3. **正確使用 HTTP 狀態碼**:2xx 成功、4xx client 錯誤、5xx server 錯誤
4. **替 API 加版本**:從第一天就為破壞性變更做規劃
5. **分頁**:大型集合一律要分頁
6. **限流**:用 rate limit 保護你的 API
7. **文件**:用 OpenAPI/Swagger 做可互動的文件

### GraphQL API

1. **Schema 優先**:寫 resolver 之前先設計 schema
2. **避免 N+1**:用 DataLoader 有效率地取資料
3. **輸入驗證**:在 schema 和 resolver 兩層都要驗證
4. **錯誤處理**:在 mutation 的 payload 裡回傳結構化的錯誤
5. **分頁**:用 cursor-based 的分頁(Relay spec)
6. **棄用**:用 `@deprecated` directive 做漸進式遷移
7. **監控**:追蹤 query 的複雜度和執行時間

## 常見陷阱

- **Over-fetching/Under-fetching(REST)**:GraphQL 解決了,但需要 DataLoader
- **破壞性變更**:替 API 加版本,或用棄用策略
- **不一致的錯誤格式**:把錯誤回應標準化
- **缺少 rate limit**:沒有限制的 API 容易被濫用
- **文件不佳**:沒有文件的 API 讓開發者很挫折
- **忽略 HTTP 語意**:把 idempotent 的操作用 POST,會違背預期
- **緊密耦合**:API 結構不該照搬資料庫 schema

英文原文

---
name: api-design-principles
description: Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.
---

# API Design Principles

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers and stand the test of time.

## When to Use This Skill

- Designing new REST or GraphQL APIs
- Refactoring existing APIs for better usability
- Establishing API design standards for your team
- Reviewing API specifications before implementation
- Migrating between API paradigms (REST to GraphQL, etc.)
- Creating developer-friendly API documentation
- Optimizing APIs for specific use cases (mobile, third-party integrations)

## Core Concepts

### 1. RESTful Design Principles

**Resource-Oriented Architecture**

- Resources are nouns (users, orders, products), not verbs
- Use HTTP methods for actions (GET, POST, PUT, PATCH, DELETE)
- URLs represent resource hierarchies
- Consistent naming conventions

**HTTP Methods Semantics:**

- `GET`: Retrieve resources (idempotent, safe)
- `POST`: Create new resources
- `PUT`: Replace entire resource (idempotent)
- `PATCH`: Partial resource updates
- `DELETE`: Remove resources (idempotent)

### 2. GraphQL Design Principles

**Schema-First Development**

- Types define your domain model
- Queries for reading data
- Mutations for modifying data
- Subscriptions for real-time updates

**Query Structure:**

- Clients request exactly what they need
- Single endpoint, multiple operations
- Strongly typed schema
- Introspection built-in

### 3. API Versioning Strategies

**URL Versioning:**

```
/api/v1/users
/api/v2/users
```

**Header Versioning:**

```
Accept: application/vnd.api+json; version=1
```

**Query Parameter Versioning:**

```
/api/users?version=1
```

## Detailed patterns and worked examples

Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.

## Best Practices

### REST APIs

1. **Consistent Naming**: Use plural nouns for collections (`/users`, not `/user`)
2. **Stateless**: Each request contains all necessary information
3. **Use HTTP Status Codes Correctly**: 2xx success, 4xx client errors, 5xx server errors
4. **Version Your API**: Plan for breaking changes from day one
5. **Pagination**: Always paginate large collections
6. **Rate Limiting**: Protect your API with rate limits
7. **Documentation**: Use OpenAPI/Swagger for interactive docs

### GraphQL APIs

1. **Schema First**: Design schema before writing resolvers
2. **Avoid N+1**: Use DataLoaders for efficient data fetching
3. **Input Validation**: Validate at schema and resolver levels
4. **Error Handling**: Return structured errors in mutation payloads
5. **Pagination**: Use cursor-based pagination (Relay spec)
6. **Deprecation**: Use `@deprecated` directive for gradual migration
7. **Monitoring**: Track query complexity and execution time

## Common Pitfalls

- **Over-fetching/Under-fetching (REST)**: Fixed in GraphQL but requires DataLoaders
- **Breaking Changes**: Version APIs or use deprecation strategies
- **Inconsistent Error Formats**: Standardize error responses
- **Missing Rate Limits**: APIs without limits are vulnerable to abuse
- **Poor Documentation**: Undocumented APIs frustrate developers
- **Ignoring HTTP Semantics**: POST for idempotent operations breaks expectations
- **Tight Coupling**: API structure shouldn't mirror database schema