Swagger Hands-on Tutorial: Book Management API
This tutorial will guide you through implementing a Swagger-based Book Management System API. The main features include:
- CRUD operations for books
- Paginated queries
- Condition-based filtering
- Automatic API documentation generation
- Online API testing
Tech stack:
- Node.js + Express
- Swagger UI Express
- Swagger JSDoc
Environment Preparation
Install Node.js
Ensure that Node.js is installed on your system (v14.0.0 or higher recommended).
Check Environment
node -v npm -v
Project Initialization
Create Project Directory
mkdir book-management-api cd book-management-api npm init -y
Install Dependencies
npm install express cors swagger-ui-express swagger-jsdoc nodemon --save
Create Basic Project Structure
book-management-api/ ├── node_modules/ ├── models/ │ └── book.js ├── routes/ │ └── books.js ├── middleware/ │ └── auth.js ├── swagger/ │ └── swagger.js ├── app.js └── package.json
Create Entry File app.js
Example
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;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// API routes
app.use('/api/books', booksRouter);
// Swagger documentation
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// Start server
app.listen(PORT, () => {
console.log(`Service started, access http://localhost:${PORT}`);
console.log(`API documentation address: http://localhost:${PORT}/api-docs`);
});
API Design and Implementation
Create Book Model
Inmodels/book.jsCreate a simple in-memory data model:
Example
let books = [
{ id: 1, title: 'Deep Understanding of JavaScript', author: 'Douglas Crockford', publishDate: '2008-01-01', isbn: '978-0596517748', category: 'Programming' },
{ id: 2, title: 'Node.js in Action', author: 'Alex Young', publishDate: '2014-08-01', isbn: '978-1617290572', category: 'Programming' },
{ id: 3, title: 'The Three-Body Problem', author: 'Liu Cixin', publishDate: '2008-01-01', isbn: '978-7536692387', category: 'Science Fiction' }
];
let nextId = 4;
module.exports = {
// Get all books
getAll: (page = 1, limit = 10, filter = {}) => {
let result = [...books];
// Apply filter conditions
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));
}
// Calculate pagination
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
return {
total: result.length,
page: page,
limit: limit,
data: result.slice(startIndex, endIndex)
};
},
// Get a single book
getById: (id) => {
return books.find(book => book.id === id);
},
// Create book
create: (book) => {
const newBook = { ...book, id: nextId++ };
books.push(newBook);
return newBook;
},
// Update book
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 book
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;
}
};
Implement Route Controller
Inroutes/books.jsImplement API routes:
Example
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: Book ID
* title:
* type: string
* description: Book Title
* author:
* type: string
* description: Author
* publishDate:
* type: string
* format: date
* description: Publication Date
* isbn:
* type: string
* description: ISBN Number
* category:
* type: string
* description: Book Category
*/
/**
* @swagger
* /api/books:
* get:
* summary: Get book list
* description: Return all books, supports pagination and filtering
* parameters:
* - in: query
* name: page
* schema:
* type: integer
* default: 1
* description: Page number
* - in: query
* name: limit
* schema:
* type: integer
* default: 10
* description: Number per page
* - in: query
* name: category
* schema:
* type: string
* description: Filter by category
* - in: query
* name: author
* schema:
* type: string
* description: Filter by author
* - in: query
* name: title
* schema:
* type: string
* description: Filter by title
* responses:
* 200:
* description: Successfully retrieved book list
* 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: Get a single book
* description: Get detailed information of a specific book by ID
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Book ID
* responses:
* 200:
* description: Successfully retrieved book
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Book'
* 404:
* description: Book not found
*/
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: 'Book not found' });
}
});
/**
* @swagger
* /api/books:
* post:
* summary: Create a new book
* description: Add a new book to the system
* 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: Book created successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Book'
* 400:
* description: Invalid input data
*/
router.post('/', (req, res) => {
// Simple validation
if (!req.body.title || !req.body.author || !req.body.isbn) {
return res.status(400).json({ message: 'Title, author, and ISBN are required fields' });
}
const newBook = Book.create(req.body);
res.status(201).json(newBook);
});
/**
* @swagger
* /api/books/{id}:
* put:
* summary: Update a book
* description: Update information of a specific book by ID
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Book 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: Book updated successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Book'
* 404:
* description: Book not found
*/
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: 'Book not found' });
}
});
/**
* @swagger
* /api/books/{id}:
* delete:
* summary: Delete a book
* description: Delete a specific book by ID
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Book ID
* responses:
* 200:
* description: Book deleted successfully
* 404:
* description: Book not found
*/
router.delete('/:id', (req, res) => {
const id = parseInt(req.params.id);
const deletedBook = Book.delete(id);
if (deletedBook) {
res.json({ message: 'Book deleted successfully', book: deletedBook });
} else {
res.status(404).json({ message: 'Book not found' });
}
});
module.exports = router;
Swagger Documentation Configuration
Configure Swagger
Createswagger/swagger.jsFile:
Example
const swaggerJsdoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Book Management API',
version: '1.0.0',
description: 'A book management system API built with Express and Swagger',
contact: {
name: 'Developer',
email: 'dev@example.com'
}
},
servers: [
{
url: 'http://localhost:3000',
description: 'Development Server'
}
]
},
// Scan all JS files containing annotations
apis: ['./routes/*.js']
};
const swaggerSpec = swaggerJsdoc(options);
module.exports = swaggerSpec;
Add Authentication Middleware
Createmiddleware/auth.js:
Example
const jwt = require('jsonwebtoken');
// Simple JWT authentication middleware
const authMiddleware = (req, res, next) => {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ message: 'No authentication token provided' });
}
try {
// In a real application, you need to verify the JWT token here
// const decoded = jwt.verify(token, process.env.JWT_SECRET);
// req.user = decoded.user;
// To simplify the tutorial, we skip verification
req.user = { id: 1, role: 'admin' };
next();
} catch (error) {
return res.status(401).json({ message: 'Invalid authentication token' });
}
};
module.exports = authMiddleware;
API Functional Testing
Start Server
Use the following command to start the server:
# 如果已配置了package.json中的scripts,执行: npm start # 或者直接使用nodemon npx nodemon app.js
6.2 Access Swagger Documentation
Open a browser and visit: http://localhost:3000/api-docs
Use Swagger to Test APIs
-
Get all books
- Click the GET /api/books endpoint
- Click the "Try it out" button
- You can set the pagination parameters page and limit, and filter conditions
- Click the "Execute" button to send the request
- Observe the results
-
Create a new book
- Click the POST /api/books endpoint
- Click the "Try it out" button
Fill in the book information in the request body, for example:
{ "title": "RESTful API设计", "author": "Martin Fowler", "publishDate": "2020-01-01", "isbn": "978-1234567890", "category": "编程" }- Click the "Execute" button to send the request
- Observe the results
-
Get, Update, and Delete
- Test other endpoints using similar methods
Troubleshooting Common Issues
Cross-Origin Issue
If the frontend application and API are not running on the same domain, you may encounter cross-origin issues. We have already configured CORS middleware at the application entry point:
app.use(cors());
If finer control is needed, you can configure it like this:
Example
origin: ['http://localhost:8080', 'https://your-frontend-domain.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
};
app.use(cors(corsOptions));
Authentication Configuration Error
Authentication issues usually appear in the following areas:
-
JWT configuration error
Ensure
JWT_SECRETEnvironment variables are set correctly:// 在应用启动时检查 if (!process.env.JWT_SECRET) { console.warn('警告: JWT_SECRET环境变量未设置,认证可能不安全'); } -
Authentication middleware used incorrectly
Make sure the middleware is correctly applied to routes that require authentication:
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) => { /* ... */ }); -
Authentication configuration in Swagger documentation
Update Swagger configuration to support Bearer Token authentication:
// swagger/swagger.js const options = { definition: { // ... 其他配置 ... components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } } }, security: [ { bearerAuth: [] } ] }, // ... 其他配置 ... }; -
Request header configuration
Ensure the client correctly sets the authentication header when making requests:
// 前端示例代码 - 使用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 Documentation Not Updating
If you update JSDoc comments but the Swagger documentation does not update, try the following solutions:
-
Ensure the path configuration is correct
// swagger/swagger.js const options = { // ... 其他配置 ... apis: ['./routes/*.js', './models/*.js'] // 确保包含所有需要生成文档的文件 }; -
Restart the server
Sometimes you need to restart the server to see the new Swagger documentation.
-
Clear browser cache
Use Ctrl+F5 to force refresh the page.
Advanced Features
Add API Versioning
Modify the application entry file:
// app.js
// ... 其他导入 ...
// API v1
app.use('/api/v1/books', booksRouter);
// 为未来的API v2预留
// app.use('/api/v2/books', booksRouterV2);
// ... 其他代码 ...
Add Request Validation
Use Express validation middleware (such asexpress-validator):
npm install express-validator --save
Then use it in the route:
Example
const { body, validationResult } = require('express-validator');
// Validation rules for creating a book
const validateBook = [
body('title').notEmpty().withMessage('Title cannot be empty'),
body('author').notEmpty().withMessage('Author cannot be empty'),
body('isbn').notEmpty().withMessage('ISBN cannot be empty')
.matches(/^(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)[\d-]+$/).withMessage('Invalid ISBN format'),
body('publishDate').optional().isDate().withMessage('Invalid publication date format'),
// Validation result handling middleware
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
}
];
// Use validation in routes
router.post('/', validateBook, (req, res) => {
// ... Code for creating a book ...
});
Add Response Compression
Use compression middleware to reduce response size:
npm install compression --save
Then add it to the application entry file:
// app.js
const compression = require('compression');
// ... 其他代码 ...
// 启用压缩
app.use(compression());
// ... 其他代码 ...
Add Response Caching
To improve performance, you can add response caching:
npm install apicache --save
Then use it at the application entry point:
// app.js
const apicache = require('apicache');
const cache = apicache.middleware;
// ... 其他代码 ...
// 缓存GET请求5分钟
app.use('/api', cache('5 minutes'));
// ... 其他代码 ...
Add Request Rate Limiting
Prevent API abuse:
npm install express-rate-limit --save
Then use it at the application entry point:
// 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);
// ... 其他代码 ... Other extensions