Skip to content

RESTful API設計の詳細

RESTful APIの詳細な設計原則と実践的なパターンを解説します。

✅ 良い例:

GET /api/users # ユーザー一覧
GET /api/users/1 # ユーザー詳細
POST /api/users # ユーザー作成
PUT /api/users/1 # ユーザー更新
DELETE /api/users/1 # ユーザー削除

❌ 悪い例:

GET /api/getUsers # 動詞を使用
POST /api/user/create # 動詞を使用
GET /api/users/1/delete # 動詞を使用

🔄 2. HTTPメソッドの適切な使用

Section titled “🔄 2. HTTPメソッドの適切な使用”

📋 HTTPメソッドの意味:

  • GET: リソースの取得(冪等性、副作用なし)
  • POST: リソースの作成(副作用あり)
  • 🔄 PUT: リソースの更新または作成(冪等性
  • 🔧 PATCH: リソースの部分更新(冪等性
  • 🗑️ DELETE: リソースの削除(冪等性

使用例:

# ユーザーの作成
POST /api/users
Content-Type: application/json
{
"name": "Alice",
"email": "alice@example.com"
}
# ユーザーの更新(全置換)
PUT /api/users/1
Content-Type: application/json
{
"name": "Alice Updated",
"email": "alice@example.com"
}
# ユーザーの部分更新
PATCH /api/users/1
Content-Type: application/json
{
"name": "Alice Updated"
}

📊 3. HTTPステータスコードの適切な使用

Section titled “📊 3. HTTPステータスコードの適切な使用”

📋 主要なステータスコード:

  • 200 OK: リクエスト成功
  • 201 Created: リソース作成成功
  • 204 No Content: リクエスト成功(レスポンスボディなし)
  • ⚠️ 400 Bad Request: リクエストが不正
  • 🔒 401 Unauthorized: 認証が必要
  • 🚫 403 Forbidden: アクセス権限がない
  • 404 Not Found: リソースが見つからない
  • ⚠️ 409 Conflict: リソースの競合
  • 🔥 500 Internal Server Error: サーバーエラー

使用例:

// 201 Created: リソース作成成功
app.post('/api/users', async (req, res) => {
const user = await createUser(req.body);
res.status(201).json(user);
});
// 204 No Content: 削除成功
app.delete('/api/users/:id', async (req, res) => {
await deleteUser(req.params.id);
res.status(204).send();
});
// 400 Bad Request: バリデーションエラー
app.post('/api/users', async (req, res) => {
const errors = validateUser(req.body);
if (errors.length > 0) {
return res.status(400).json({ errors });
}
// ...
});
GET /api/v1/users
GET /api/v2/users

✅ メリット:

  • 明確で分かりやすい
  • キャッシュが容易

❌ デメリット:

  • URLが長くなる

📋 ヘッダーベースのバージョニング

Section titled “📋 ヘッダーベースのバージョニング”
GET /api/users
Accept: application/vnd.api+json;version=1

✅ メリット:

  • URLがシンプル
  • バージョン管理が柔軟

❌ デメリット:

  • キャッシュが複雑
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
}

実装例:

class ApiError extends Error {
constructor(
public statusCode: number,
public code: string,
message: string,
public details?: any
) {
super(message);
}
}
app.use((err: ApiError, req: Request, res: Response, next: NextFunction) => {
res.status(err.statusCode || 500).json({
error: {
code: err.code || 'INTERNAL_ERROR',
message: err.message,
details: err.details
}
});
});

RESTful API設計の詳細のポイント:

  • リソースベースのURL: 名詞を使用し、動詞を避ける
  • HTTPメソッド: 適切なメソッドを使用
  • ステータスコード: 適切なステータスコードを使用
  • バージョニング: URLまたはヘッダーでバージョン管理
  • エラーハンドリング: 統一されたエラーレスポンス構造

適切なRESTful API設計により、使いやすく保守しやすいAPIを構築できます。