Swagger実践チュートリアル:図書管理API

このチュートリアルでは、Swaggerベースの図書管理システムAPIを実装します。主な機能は次のとおりです。

  • 図書のCRUD操作(追加・削除・更新・検索)
  • ページネーション検索
  • 条件フィルタリング
  • APIドキュメントの自動生成
  • オンラインAPIテスト

技術スタック:

  • Node.js + Express
  • Swagger UI Express
  • Swagger JSDoc

環境準備

Node.jsのインストール

システムにNode.jsがインストールされていることを確認してください(v14.0.0以降を推奨)。

環境の確認

node -v
npm -v

プロジェクトの初期化

プロジェクトディレクトリの作成

mkdir book-management-api
cd book-management-api
npm init -y

依存パッケージのインストール

npm install express cors swagger-ui-express swagger-jsdoc nodemon --save

基本プロジェクト構造の作成

book-management-api/
├── node_modules/
├── models/
│   └── book.js
├── routes/
│   └── books.js
├── middleware/
│   └── auth.js
├── swagger/
│   └── swagger.js
├── app.js
└── package.json

エントリファイル app.js の作成

例

const express = require('express');
const cors = require('cors');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./swagger/swagger');
const booksRouter = require('./routes/books');

const app = express();
const PORT = process.env.PORT || 3000;

// ミドルウェア
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// APIルート
app.use('/api/books', booksRouter);

// Swaggerドキュメント
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

// サーバー起動
app.listen(PORT, () => {
  console.log(`サービスが起動しました。アクセス http://localhost:${PORT}`);
  console.log(`APIドキュメントのアドレス: http://localhost:${PORT}/api-docs`);
});

APIの設計と実装

図書モデルの作成

にmodels/book.js中に簡単なメモリ内データモデルを作成します:

例

// models/book.js
let books = [
  { id: 1, title: 'JavaScriptを深く理解する', author: 'Douglas Crockford', publishDate: '2008-01-01', isbn: '978-0596517748', category: 'プログラミング' },
  { id: 2, title: 'Node.js実践', author: 'Alex Young', publishDate: '2014-08-01', isbn: '978-1617290572', category: 'プログラミング' },
  { id: 3, title: '三体', author: '劉慈欣', publishDate: '2008-01-01', isbn: '978-7536692387', category: 'SF' }
];

let nextId = 4;

module.exports = {
  // すべての図書を取得
  getAll: (page = 1, limit = 10, filter = {}) => {
    let result = [...books];
   
    // フィルター条件を適用
    if (filter.category) {
      result = result.filter(book => book.category === filter.category);
    }
   
    if (filter.author) {
      result = result.filter(book => book.author.includes(filter.author));
    }
   
    if (filter.title) {
      result = result.filter(book => book.title.includes(filter.title));
    }
   
    // ページネーションを計算
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
   
    return {
      total: result.length,
      page: page,
      limit: limit,
      data: result.slice(startIndex, endIndex)
    };
  },
 
  // 単一の図書を取得
  getById: (id) => {
    return books.find(book => book.id === id);
  },
 
  // 図書を作成
  create: (book) => {
    const newBook = { ...book, id: nextId++ };
    books.push(newBook);
    return newBook;
  },
 
  // 図書を更新
  update: (id, bookData) => {
    const index = books.findIndex(book => book.id === id);
    if (index !== -1) {
      books[index] = { ...books[index], ...bookData };
      return books[index];
    }
    return null;
  },
 
  // 図書を削除
  delete: (id) => {
    const index = books.findIndex(book => book.id === id);
    if (index !== -1) {
      const deletedBook = books[index];
      books.splice(index, 1);
      return deletedBook;
    }
    return null;
  }
};

ルートコントローラーの実装

にroutes/books.jsにAPIルートを実装します:

例

// routes/books.js
const express = require('express');
const router = express.Router();
const Book = require('../models/book');

/**
 * @swagger
 * components:
 *   schemas:
 *     Book:
 *       type: object
 *       required:
 *         - title
 *         - author
 *         - isbn
 *       properties:
 *         id:
 *           type: integer
* description: 図書ID
 *         title:
 *           type: string
* description: 図書タイトル
 *         author:
 *           type: string
* description: 著者
 *         publishDate:
 *           type: string
 *           format: date
* description: 出版日
 *         isbn:
 *           type: string
* description: ISBN番号
 *         category:
 *           type: string
* description: 図書分類
 */


/**
 * @swagger
 * /api/books:
 *   get:
* summary: 図書リストを取得
* description: すべての図書を返します。ページネーションとフィルタリングに対応
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
* description: ページ番号
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
* description: 1ページあたりの件数
 *       - in: query
 *         name: category
 *         schema:
 *           type: string
* description: 分類でフィルタリング
 *       - in: query
 *         name: author
 *         schema:
 *           type: string
* description: 著者でフィルタリング
 *       - in: query
 *         name: title
 *         schema:
 *           type: string
* description: タイトルでフィルタリング
 *     responses:
 *       200:
* description: 図書リストの取得成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 total:
 *                   type: integer
 *                 page:
 *                   type: integer
 *                 limit:
 *                   type: integer
 *                 data:
 *                   type: array
 *                   items:
 *                     $ref: '#/components/schemas/Book'
 */

router.get('/', (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const filter = {};
 
  if (req.query.category) filter.category = req.query.category;
  if (req.query.author) filter.author = req.query.author;
  if (req.query.title) filter.title = req.query.title;
 
  const result = Book.getAll(page, limit, filter);
  res.json(result);
});

/**
 * @swagger
 * /api/books/{id}:
 *   get:
* summary: 単一の図書を取得
* description: IDで特定の図書の詳細情報を取得
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
* description: 図書ID
 *     responses:
 *       200:
* description: 図書の取得成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Book'
 *       404:
* description: 図書が存在しません
 */

router.get('/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const book = Book.getById(id);
 
  if (book) {
    res.json(book);
  } else {
    res.status(404).json({ message: '図書が存在しません' });
  }
});

/**
 * @swagger
 * /api/books:
 *   post:
* summary: 新しい図書を作成
* description: 新しい図書をシステムに追加
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - title
 *               - author
 *               - isbn
 *             properties:
 *               title:
 *                 type: string
 *               author:
 *                 type: string
 *               publishDate:
 *                 type: string
 *                 format: date
 *               isbn:
 *                 type: string
 *               category:
 *                 type: string
 *     responses:
 *       201:
* description: 図書の作成成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Book'
 *       400:
* description: 入力データが無効です
 */

router.post('/', (req, res) => {
  // 簡易検証
  if (!req.body.title || !req.body.author || !req.body.isbn) {
    return res.status(400).json({ message: 'タイトル、著者、ISBNは必須項目です' });
  }
 
  const newBook = Book.create(req.body);
  res.status(201).json(newBook);
});

/**
 * @swagger
 * /api/books/{id}:
 *   put:
* summary: 図書を更新
* description: IDで特定の図書の情報を更新
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
* description: 図書ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               title:
 *                 type: string
 *               author:
 *                 type: string
 *               publishDate:
 *                 type: string
 *                 format: date
 *               isbn:
 *                 type: string
 *               category:
 *                 type: string
 *     responses:
 *       200:
* description: 図書の更新成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Book'
 *       404:
* description: 図書が存在しません
 */

router.put('/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const updatedBook = Book.update(id, req.body);
 
  if (updatedBook) {
    res.json(updatedBook);
  } else {
    res.status(404).json({ message: '図書が存在しません' });
  }
});

/**
 * @swagger
 * /api/books/{id}:
 *   delete:
* summary: 図書を削除
* description: IDで特定の図書を削除
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
* description: 図書ID
 *     responses:
 *       200:
* description: 図書の削除成功
 *       404:
* description: 図書が存在しません
 */

router.delete('/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const deletedBook = Book.delete(id);
 
  if (deletedBook) {
    res.json({ message: '図書が削除されました', book: deletedBook });
  } else {
    res.status(404).json({ message: '図書が存在しません' });
  }
});

module.exports = router;

Swaggerドキュメントの設定

Swaggerの設定

作成swagger/swagger.jsファイル:

例

// swagger/swagger.js
const swaggerJsdoc = require('swagger-jsdoc');

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: '図書管理API',
      version: '1.0.0',
      description: 'ExpressとSwaggerで構築した図書管理システムAPI',
      contact: {
        name: '開発者',
        email: 'dev@example.com'
      }
    },
    servers: [
      {
        url: 'http://localhost:3000',
        description: '開発サーバー'
      }
    ]
  },
  // アノテーションを含むすべてのJSファイルをスキャン
  apis: ['./routes/*.js']
};

const swaggerSpec = swaggerJsdoc(options);

module.exports = swaggerSpec;

認証ミドルウェアの追加

作成middleware/auth.js:

例

// middleware/auth.js
const jwt = require('jsonwebtoken');

// 簡易JWT検証ミドルウェア
const authMiddleware = (req, res, next) => {
  const token = req.header('Authorization')?.replace('Bearer ', '');
 
  if (!token) {
    return res.status(401).json({ message: '認証トークンが提供されていません' });
  }
 
  try {
    // 実際のアプリケーションでは、ここでJWTトークンを検証する必要があります
    // const decoded = jwt.verify(token, process.env.JWT_SECRET);
    // req.user = decoded.user;
   
    // チュートリアルを簡略化するため、検証をスキップします
    req.user = { id: 1, role: 'admin' };
    next();
  } catch (error) {
    return res.status(401).json({ message: '無効な認証トークン' });
  }
};

module.exports = authMiddleware;

API機能テスト

サービスの起動

以下のコマンドでサービスを起動します:

# 如果已配置了package.json中的scripts,执行:
npm start

# 或者直接使用nodemon
npx nodemon app.js

6.2 Swaggerドキュメントへのアクセス

ブラウザで http://localhost:3000/api-docs にアクセスします:

Swaggerを使用したAPIテスト

  1. すべての図書を取得

    • GET /api/books インターフェースをクリック
    • "Try it out" ボタンをクリック
    • ページネーションパラメータ page と limit、およびフィルター条件を設定できます
    • "Execute" ボタンをクリックしてリクエストを送信
    • 結果を確認
  2. 新しい図書を作成

    • POST /api/books インターフェースをクリック
    • "Try it out" ボタンをクリック
    • リクエストボディに図書情報を入力します。例:

      {
          "title": "RESTful API设计",
          "author": "Martin Fowler",
          "publishDate": "2020-01-01",
          "isbn": "978-1234567890",
          "category": "编程"
      }
      
    • "Execute" ボタンをクリックしてリクエストを送信
    • 結果を確認
  3. 取得、更新、削除

    • 同様の方法で他のAPIをテスト

よくある問題のトラブルシューティング

クロスオリジン問題

フロントエンドアプリケーションとAPIが同じドメインで実行されていない場合、クロスドメイン問題が発生する可能性があります。アプリケーションのエントリポイントでCORSミドルウェアをすでに設定しています。

app.use(cors());

より細かい制御が必要な場合は、次のように設定できます:

例

const corsOptions = {
  origin: ['http://localhost:8080', 'https://your-frontend-domain.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
};

app.use(cors(corsOptions));

認証設定エラー

認証の問題は通常、以下の側面で発生します:

  1. JWT設定エラー

    確認してくださいJWT_SECRET環境変数が正しく設定されていること:

    // 在应用启动时检查
    if (!process.env.JWT_SECRET) {
      console.warn('警告: JWT_SECRET环境变量未设置,认证可能不安全');
    }        
    
  2. 認証ミドルウェアの使用エラー

    認証が必要なルートにミドルウェアを正しく適用してください:

    const auth = require('../middleware/auth');
    
    // 公开路由 - 无需认证
    router.get('/', (req, res) => { /* ... */ });
    
    // 受保护路由 - 需要认证
    router.post('/', auth, (req, res) => { /* ... */ });
    router.put('/:id', auth, (req, res) => { /* ... */ });
    router.delete('/:id', auth, (req, res) => { /* ... */ });
    
  3. Swaggerドキュメント内の認証設定

    Bearer Token認証をサポートするようにSwagger設定を更新します:

    // swagger/swagger.js
    const options = {
      definition: {
        // ... 其他配置 ...
        components: {
          securitySchemes: {
            bearerAuth: {
              type: 'http',
              scheme: 'bearer',
              bearerFormat: 'JWT'
            }
          }
        },
        security: [
          {
            bearerAuth: []
          }
        ]
      },
      // ... 其他配置 ...
    };
    
  4. リクエストヘッダー設定

    クライアントがリクエスト時に認証ヘッダーを正しく設定していることを確認してください:

    // 前端示例代码 - 使用fetch API
    const token = localStorage.getItem('token');
    
    fetch('http://localhost:3000/api/books', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(bookData)
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('错误:', error));
    

Swaggerドキュメントが更新されない

JSDocコメントを更新してもSwaggerドキュメントが更新されない場合は、次の解決策を試してください:

  1. パス設定が正しいことを確認してください

    // swagger/swagger.js
    const options = {
      // ... 其他配置 ...
      apis: ['./routes/*.js', './models/*.js'] // 确保包含所有需要生成文档的文件
    };
    
  2. サーバーを再起動します

    新しいSwaggerドキュメントを表示するには、サーバーの再起動が必要な場合があります。

  3. ブラウザのキャッシュをクリアします

    Ctrl+F5を使用してページを強制更新します。


高度な機能

APIバージョン管理の追加

アプリケーションのエントリポイントファイルを変更します:

// app.js
// ... 其他导入 ...

// API v1
app.use('/api/v1/books', booksRouter);

// 为未来的API v2预留
// app.use('/api/v2/books', booksRouterV2);

// ... 其他代码 ...

リクエスト検証の追加

Express検証ミドルウェア(例:express-validator):

npm install express-validator --save

次にルートで使用します:

例

// routes/books.js
const { body, validationResult } = require('express-validator');

// 書籍作成の検証ルール
const validateBook = [
  body('title').notEmpty().withMessage('タイトルは空にできません'),
  body('author').notEmpty().withMessage('著者は空にできません'),
  body('isbn').notEmpty().withMessage('ISBNは空にできません')
    .matches(/^(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)[\d-]+$/).withMessage('ISBNの形式が無効です'),
  body('publishDate').optional().isDate().withMessage('出版日の形式が無効です'),
 
  // 検証結果処理ミドルウェア
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  }
];

// ルートで検証を使用
router.post('/', validateBook, (req, res) => {
  // ... 書籍作成のコード ...
});

レスポンス圧縮の追加

圧縮ミドルウェアを使用してレスポンスサイズを削減します:

npm install compression --save

次にアプリケーションのエントリポイントファイルに追加します:

// app.js
const compression = require('compression');

// ... 其他代码 ...

// 启用压缩
app.use(compression());

// ... 其他代码 ...

レスポンスキャッシュの追加

パフォーマンスを向上させるために、レスポンスキャッシュを追加できます:

npm install apicache --save

次にアプリケーションのエントリポイントで使用します:

// app.js
const apicache = require('apicache');
const cache = apicache.middleware;

// ... 其他代码 ...

// 缓存GET请求5分钟
app.use('/api', cache('5 minutes'));

// ... 其他代码 ...

リクエストレート制限の追加

APIの不正使用を防ぐ:

npm install express-rate-limit --save

次にアプリケーションのエントリポイントで使用します:

// app.js
const rateLimit = require('express-rate-limit');

// ... 其他代码 ...

// 创建限流中间件
const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 每个IP在windowMs时间内最多100个请求
  message: '来自此IP的请求过多,请稍后再试'
});

// 应用限流中间件
app.use('/api', apiLimiter);

// ... 其他代码 ...
その他の拡張