mcpField

api-documentation-writer

github.com/eddiebe147開発50 回インストール
リポジトリ

api-documentation-writer について

api-documentation-writer は、API ドキュメントを作成・保守する開発者向けのスキルです。OpenAPI/Swagger 仕様、エンドポイント、認証、エラー、変更履歴、多言語のコード例を扱います。

主な機能

  1. 01OpenAPI/Swagger 仕様
  2. 02エンドポイントと認証のリファレンス
  3. 03エラーコードと対処方法
  4. 04多言語のコード例
  5. 05変更履歴とインタラクティブドキュメント

活用シーン

  1. 01新しい API やエンドポイントの文書化
  2. 02認証・エラーガイドの作成
  3. 03複数言語のコード例の追加
  4. 04API 変更履歴の管理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/eddiebe147/claude-settings --skill api-documentation-writer

インストール後、Claude Code で/api-documentation-writerを入力して読み込まれたか確認します。

詳細

API ドキュメント作成スキル

概要

このスキルを使うと、開発者に喜ばれる、明確で包括的な API ドキュメントを作成できます。OpenAPI/Swagger の仕様、エンドポイントリファレンス、認証ガイド、複数の言語によるコード例、開発者エクスペリエンスのベストプラクティスを扱います。

ドキュメント作成の理念

3 つの C
  1. Clear(明確):曖昧さがなく、専門用語に頼らない説明
  2. Complete(完全):すべてのパラメーター、レスポンス、エッジケースを記載
  3. Current(最新):実際の API の動作と常に同期
ドキュメントに記載する内容
  • 記載する:すべての公開エンドポイントを記載する
  • 記載する:あらゆるシナリオのリクエスト/レスポンス例を含める
  • 記載する:エラーコードとその解決手順を記載する
  • 記載する:よく使われる言語でコード例を提供する
  • 記載しない:内部/非公開エンドポイントを記載しない
  • 記載しない:読者がドメインについて知っていると想定しない
  • 記載しない:ドキュメントを実装と乖離させない

OpenAPI 仕様

基本構造
# openapi.yaml
openapi: 3.1.0
info:
  title: My API
  version: 1.0.0
  description: |
    Welcome to the My API documentation.

    ## Getting Started
    1. Sign up for an API key at [dashboard.example.com](https://dashboard.example.com)
    2. Include your key in the `Authorization` header
    3. Start making requests!

    ## Rate Limits
    - Free tier: 100 requests/minute
    - Pro tier: 1000 requests/minute
  contact:
    name: API Support
    email: [email protected]
    url: https://support.example.com
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT

servers:
  - url: https://api.example.com/v1
    description: Production
  - url: https://staging-api.example.com/v1
    description: Staging

tags:
  - name: Users
    description: User management operations
  - name: Items
    description: Item CRUD operations
エンドポイントのドキュメント
paths:
  /users:
    get:
      tags:
        - Users
      summary: List all users
      description: |
        Retrieves a paginated list of users. Results are sorted by creation date (newest first).

        **Permissions required:** `users:read`
      operationId: listUsers
      parameters:
        - name: page
          in: query
          description: Page number (1-indexed)
          required: false
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
        - name: limit
          in: query
          description: Number of results per page (max 100)
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
          example: 20
        - name: status
          in: query
          description: Filter by user status
          required: false
          schema:
            type: string
            enum: [active, inactive, pending]
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'
              example:
                data:
                  - id: "usr_123"
                    email: "[email protected]"
                    name: "John Doe"
                    status: "active"
                    created_at: "2024-01-15T10:30:00Z"
                meta:
                  page: 1
                  limit: 20
                  total: 150
                  total_pages: 8
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/RateLimited'

    post:
      tags:
        - Users
      summary: Create a new user
      description: |
        Creates a new user account. An email verification will be sent to the provided address.

        **Permissions required:** `users:write`
      operationId: createUser
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
            examples:
              basic:
                summary: Basic user creation
                value:
                  email: "[email protected]"
                  name: "Jane Doe"
              with_metadata:
                summary: User with metadata
                value:
                  email: "[email protected]"
                  name: "Jane Doe"
                  metadata:
                    department: "Engineering"
                    role: "Developer"
      responses:
        '201':
          description: User created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          $ref: '#/components/responses/BadRequest'
        '409':
          description: User with this email already exists
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  code: "USER_EXISTS"
                  message: "A user with this email already exists"
スキーマ定義
components:
  schemas:
    User:
      type: object
      description: Represents a user in the system
      required:
        - id
        - email
        - status
        - created_at
      properties:
        id:
          type: string
          description: Unique identifier (prefixed with `usr_`)
          pattern: '^usr_[a-zA-Z0-9]+$'
          example: "usr_123abc"
        email:
          type: string
          format: email
          description: User's email address (unique)
          example: "[email protected]"
        name:
          type: string
          description: User's display name
          maxLength: 100
          example: "John Doe"
        status:
          type: string
          enum: [active, inactive, pending]
          description: |
            Account status:
            - `active`: User can sign in and use the service
            - `inactive`: Account has been deactivated
            - `pending`: Awaiting email verification
          example: "active"
        metadata:
          type: object
          additionalProperties: true
          description: Custom key-value pairs for storing additional data
          example:
            department: "Engineering"
        created_at:
          type: string
          format: date-time
          description: ISO 8601 timestamp of account creation
          example: "2024-01-15T10:30:00Z"
        updated_at:
          type: string
          format: date-time
          description: ISO 8601 timestamp of last update
          example: "2024-01-16T14:45:00Z"

    CreateUserRequest:
      type: object
      required:
        - email
      properties:
        email:
          type: string
          format: email
          description: Email address for the new user (must be unique)
        name:
          type: string
          description: User's display name
          maxLength: 100
        metadata:
          type: object
          additionalProperties: true

    Error:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - message
          properties:
            code:
              type: string
              description: Machine-readable error code
            message:
              type: string
              description: Human-readable error description
            details:
              type: array
              description: Additional error details for validation errors
              items:
                type: object
                properties:
                  field:
                    type: string
                  message:
                    type: string
認証のドキュメント
components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        JWT token obtained from the `/auth/token` endpoint.

        Include in requests as:
        ```
        Authorization: Bearer <your-token>
        ```

        Tokens expire after 1 hour. Use refresh tokens for long-lived sessions.

    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: |
        API key for server-to-server communication.

        Obtain your key from the [Developer Dashboard](https://dashboard.example.com).

        Include in requests as:
        ```
        X-API-Key: <your-api-key>
        ```

security:
  - BearerAuth: []
  - ApiKeyAuth: []
再利用可能なレスポンス
components:
  responses:
    BadRequest:
      description: Invalid request parameters
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            validation_error:
              summary: Validation error
              value:
                error:
                  code: "VALIDATION_ERROR"
                  message: "Request validation failed"
                  details:
                    - field: "email"
                      message: "Must be a valid email address"
            missing_field:
              summary: Missing required field
              value:
                error:
                  code: "MISSING_FIELD"
                  message: "Required field 'email' is missing"

    Unauthorized:
      description: Missing or invalid authentication
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: "UNAUTHORIZED"
              message: "Invalid or expired authentication token"

    Forbidden:
      description: Insufficient permissions
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: "FORBIDDEN"
              message: "You don't have permission to access this resource"

    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: "NOT_FOUND"
              message: "The requested resource was not found"

    RateLimited:
      description: Rate limit exceeded
      headers:
        X-RateLimit-Limit:
          schema:
            type: integer
          description: Request limit per minute
        X-RateLimit-Remaining:
          schema:
            type: integer
          description: Remaining requests in current window
        X-RateLimit-Reset:
          schema:
            type: integer
          description: Unix timestamp when the rate limit resets
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: "RATE_LIMITED"
              message: "Too many requests. Please retry after 60 seconds"

Markdown ドキュメント

エンドポイントリファレンスのテンプレート
# Create User

Create a new user account.

## Endpoint

POST /v1/users


## Authentication

Requires API key with `users:write` permission.

## Request Body

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `email` | string | Yes | User's email address (must be unique) |
| `name` | string | No | Display name (max 100 characters) |
| `metadata` | object | No | Custom key-value pairs |

### Example Request

```bash
curl -X POST https://api.example.com/v1/users \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "name": "Jane Doe"
  }'

レスポンス

成功(201 Created)
{
  "id": "usr_abc123",
  "email": "[email protected]",
  "name": "Jane Doe",
  "status": "pending",
  "created_at": "2024-01-15T10:30:00Z"
}
エラー
ステータスコード説明
400VALIDATION_ERRORメールアドレスの形式が無効、または必須フィールドがありません
401UNAUTHORIZED認証が無効、または認証情報がありません
409USER_EXISTSこのメールアドレスのユーザーはすでに存在します
429RATE_LIMITEDリクエストが多すぎます
エラーの例
{
  "error": {
    "code": "USER_EXISTS",
    "message": "A user with this email already exists"
  }
}

## Code Examples

### Multi-Language Examples

```markdown
## Code Examples

### cURL

```bash
curl -X GET "https://api.example.com/v1/users?limit=10" \
  -H "Authorization: Bearer YOUR_TOKEN"
JavaScript(fetch)
const response = await fetch('https://api.example.com/v1/users?limit=10', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN'
  }
});

const data = await response.json();
console.log(data);
JavaScript(axios)
import axios from 'axios';

const { data } = await axios.get('https://api.example.com/v1/users', {
  params: { limit: 10 },
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN'
  }
});
Python
import requests

response = requests.get(
    'https://api.example.com/v1/users',
    params={'limit': 10},
    headers={'Authorization': 'Bearer YOUR_TOKEN'}
)

data = response.json()
print(data)
Ruby
require 'net/http'
require 'json'

uri = URI('https://api.example.com/v1/users?limit=10')
request = Net::HTTP::Get.new(uri)
request['Authorization'] = 'Bearer YOUR_TOKEN'

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(request)
end

data = JSON.parse(response.body)
puts data
Go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    req, _ := http.NewRequest("GET", "https://api.example.com/v1/users?limit=10", nil)
    req.Header.Set("Authorization", "Bearer YOUR_TOKEN")

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    var data map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&data)
    fmt.Println(data)
}

## Error Documentation

### Error Code Reference

```markdown
# Error Codes

All API errors follow a consistent format:

```json
{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable description",
    "details": []  // Optional additional information
  }
}

認証エラー

コードHTTP ステータス説明解決方法
UNAUTHORIZED401トークンがないか、無効です有効な Authorization ヘッダーを含めてください
TOKEN_EXPIRED401トークンの有効期限が切れています/auth/token を使って新しいトークンを取得してください
INVALID_API_KEY401API キーが認識されませんダッシュボードで API キーを確認してください
FORBIDDEN403権限が不足していますトークンに適切なスコープをリクエストしてください

検証エラー

コードHTTP ステータス説明解決方法
VALIDATION_ERROR400リクエストボディの検証に失敗しました該当するフィールドを確認するには、details 配列を確認してください
MISSING_FIELD400必須フィールドが指定されていませんすべての必須フィールドを含めてください
INVALID_FORMAT400フィールドの形式が正しくありません期待される形式に合わせてください(スキーマを参照)

リソースエラー

コードHTTP ステータス説明解決方法
NOT_FOUND404リソースが存在しませんリソース ID が正しいことを確認してください
ALREADY_EXISTS409リソースはすでに存在します別の識別子を使うか、既存のリソースを更新してください
CONFLICT409状態が競合しています更新してから操作を再試行してください

レート制限

コードHTTP ステータス説明解決方法
RATE_LIMITED429リクエストが多すぎます待ってから再試行してください(Retry-After ヘッダーを参照)

## Changelog Documentation

### API Changelog Format

```markdown
# API Changelog

## 2024-01-15 - v1.2.0

### Added
- `GET /users/{id}/activity` - Retrieve user activity history
- `metadata` field on User object for custom data storage

### Changed
- Pagination now 1-indexed (previously 0-indexed)
- Rate limits increased: Free tier 100 → 200 req/min

### Deprecated
- `GET /users/search` - Use `GET /users` with query parameters instead
  - Will be removed in v2.0.0

### Fixed
- `created_at` now correctly returns UTC timezone

---

## 2024-01-01 - v1.1.0

### Added
- Webhook support for user events
- `status` filter on `GET /users`

### Security
- API keys now support IP allowlisting

インタラクティブドキュメント

Swagger UI の設定
// swagger-config.js
const swaggerUiOptions = {
  customCss: '.swagger-ui .topbar { display: none }',
  customSiteTitle: 'API Documentation',
  customfavIcon: '/favicon.ico',
  swaggerOptions: {
    persistAuthorization: true,
    displayRequestDuration: true,
    filter: true,
    tryItOutEnabled: true,
  },
};
Redoc の設定
# redoc.yaml
x-tagGroups:
  - name: Getting Started
    tags:
      - Authentication
  - name: Core Resources
    tags:
      - Users
      - Items
  - name: Utilities
    tags:
      - Webhooks
      - Health

x-logo:
  url: 'https://example.com/logo.png'
  altText: 'API Logo'

ドキュメントのチェックリスト

エンドポイントごと
  • 概要(1 行)
  • 説明(詳細な解説)
  • すべてのパラメーターを型と例とともに記載
  • すべてのレスポンスコードを例とともに記載
  • エラーコードとその解決手順
  • 少なくとも 2 つの言語によるコード例
  • 認証要件を明記
API 全体
  • スタートガイド
  • 例を含む認証ガイド
  • レート制限のドキュメント
  • ページネーションのパターン
  • エラー処理ガイド
  • 変更履歴の管理
  • バージョニング戦略の記載
  • SDK/ライブラリへのリンク
開発者エクスペリエンス
  • インタラクティブな「試してみる」機能
  • コピーしてすぐに使えるサンプル
  • 用語の統一
  • 検索機能
  • モバイルフレンドリーな表示

ツールの統合

コードから生成
# From Express/Node.js routes
npx swagger-jsdoc -d swaggerDef.js -o openapi.yaml

# From TypeScript types
npx openapi-typescript-codegen --input openapi.yaml --output ./sdk
OpenAPI の検証
# Validate spec
npx @redocly/cli lint openapi.yaml

# Preview documentation
npx @redocly/cli preview-docs openapi.yaml

このスキルを使用する場面

次の場合にこのスキルを呼び出します:

  • API ドキュメントをゼロから新規作成するとき
  • 新しいエンドポイントのドキュメントを追加するとき
  • OpenAPI/Swagger 仕様を書くとき
  • 複数の言語でコードサンプルを作成するとき
  • 認証フローをドキュメント化するとき
  • 開発者ポータルを構築するとき
  • 既存の API ドキュメントを改善するとき
  • インタラクティブなドキュメント(Swagger UI、Redoc)を設定するとき

コメント