Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swagger Practical Tutorial: Book Management API

Swagger Practical Tutorial: Book Management API

This tutorial will guide you to implement a Swagger-based book management system API, with main features including:

Tech stack:


Environment Preparation

Install Node.js

Ensure that Node.js is installed on your system (version 14.0.0 or higher is recommended).

Check the environment



node -v

npm -v


Project initialization

Create the 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 the 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 the entry file app.js

Example

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

;

// 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 the server

app.

listen

(

PORT

,

(

)

=>

{

  console.

log

(

`Server started, access http

:

//localhost:${PORT}`);

  console.

log

(

`API documentation address

:

http

:

//localhost:${PORT}/api-docs`);

}

)

;


API design and implementation

Create the book model

inmodels/book.js Create a simple in-memory data model in:

Example

// models/book.js

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 a book

  create

:

(

book

)

=>

{

   

const

newBook

=

{

...

book

,

id

:

nextId

++

}

;

    books.

push

(

newBook

)

;

   

return

newBook

;

 

}

,

 

 

// Update a 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 a 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 the route controller

in routes/books.js Implement API routes in:

Example

// 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: 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, with support for 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: Items 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 does not exist
 */

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 does not exist'

}

)

;

 

}

}

)

;

/**
 * @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 the 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 does not exist
 */

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 does not exist'

}

)

;

 

}

}

)

;

/**
 * @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 does not exist
 */

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 does not exist'

}

)

;

 

}

}

)

;

module.

exports

=

router

;


Swagger documentation configuration

Configure Swagger

creation swagger/swagger.js File:

Example

// swagger/swagger.js

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

creation middleware/auth.js:

Example

// middleware/auth.js

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

:

'Authentication token not provided'

}

)

;

 

}

 

 

try

{

   

// In a real application, the JWT token needs to be verified 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

;


Interface function testing

Start the service

Start the service using the following command:



# If scripts are configured in package.json, execute:

npm start



# Or use nodemon directly

npx nodemon app.js

6.2 Access the Swagger documentation

Open the browser and visit: http://localhost:3000/api-docs

Test the interface using Swagger

  1. Get all books

  2. Click the GET /api/books interface
  3. Click the "Try it out" button
  4. You can set the pagination parameters page and limit, as well as filter conditions
  5. Click the "Execute" button to send the request
  6. Observe results
  7. - Click the GET /api/books interface - Click the "Try it out" button - You can set pagination parameters page and limit, as well as filter conditions - Click the "Execute" button to send the request - Observe the result
    1. Create a new book

    2. Click the POST /api/books interface
    3. Click the "Try it out" button
    4. 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": "编程"
      
      }
      
      
    5. Click the "Execute" button to send the request
    6. Observe results
    7. - Click the POST /api/books interface - 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 result
      1. Get, update, and delete

      2. Use similar methods to test other interfaces
      3. - Use similar methods to test other interfaces

        Troubleshooting common problems

        Cross-origin issues

        If the front-end application and the API do not run under the same domain, you may encounter cross-origin issues. We have configured the CORS middleware at the application entry point:

        
        
        app.use(cors());
        
        

        If finer control is needed, you can configure it like this:

        Example

        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

        )

        )

        ;

        Authentication configuration errors

        Authentication problems usually appear in the following aspects:

        1. JWT configuration errors

          Make sure JWT_SECRET The environment variables have been set correctly:

        // Check at application startup if (!process.env.JWT_SECRET) { console.warn('Warning: JWT_SECRET environment variable not set, authentication may be insecure'); }
        2.

        Incorrect use of authentication middleware

        Ensure that 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) => { / ... */ });

        3.

        Authentication configuration in the Swagger document

        Update the Swagger configuration to support Bearer Token authentication:

        // swagger/swagger.js
        
        const options = {
        
        definition: {
        
        // ... other configurations ...
        
        components: {
        
        securitySchemes: {
        
        bearerAuth: {
        
        type: 'http',
        
        scheme: 'bearer',
        
        bearerFormat: 'JWT'
        
        }
        
        }
        
        },
        
        security: [
        
        {
        
        bearerAuth: []
        
        }
        
        ]
        
        },
        
        // ... other configurations ...
        
        };
        
        
        4.

        Request header configuration

        Ensure that the authentication header is correctly set when the client makes a request:

        // 前端示例代码 - 使用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 document does not update

        If you updated the JSDoc comments but the Swagger document is not updated, try the following solutions:

        1. Ensure that the path configuration is correct

        // swagger/swagger.js const options = { // ... other configuration ... apis: ['./routes/.js', './models/.js'] // ensure all files that need documentation generation are included }; 2.

        Restart the server

        Sometimes you need to restart the server to see the new Swagger document.

        3.

        Clear the browser cache

        Use Ctrl+F5 to force a refresh of the page.


        Advanced features

        Add API version control

        Modify the application entry file:

        // app.js
        
        // ... other imports ...
        
        
        
        // API v1
        
        app.use('/api/v1/books', booksRouter);
        
        
        
        // Reserved for future API v2
        
        // app.use('/api/v2/books', booksRouterV2);
        
        
        
        // ... other code ...
        
        

        Add request validation

        Use the Express validation middleware (such asexpress-validator):

        npm install express-validator --save
        
        

        Then use it in the route:

        Example

        // routes/books.js

        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'

        )

        ,

         

         

        // Middleware for handling validation results

         

        (

        req

        ,

        res

        ,

        next

        )

        =>

        {

           

        const

        errors

        =

        validationResult

        (

        req

        )

        ;

           

        if

        (

        !

        errors.

        isEmpty

        (

        )

        )

        {

             

        return

        res.

        status

        (

        400

        )

        .

        json

        (

        {

        errors

        :

        errors.

        array

        (

        )

        }

        )

        ;

           

        }

            next

        (

        )

        ;

         

        }

        ]

        ;

        // Use validation in the route

        router.

        post

        (

        '/'

        ,

        validateBook

        ,

        (

        req

        ,

        res

        )

        =>

        {

         

        // ... code for creating a book ...

        }

        )

        ;

        Add response compression

        Use compression middleware to reduce the response size:

        
        
        npm install compression --save
        
        

        Then add it in the application entry file:

        // app.js
        
        const compression = require('compression');
        
        
        
        // ... other code ...
        
        
        
        // Enable compression
        
        app.use(compression());
        
        
        
        // ... other code ...
        
        

        Add response caching

        To improve performance, you can add response caching:

        
        
        npm install apicache --save
        
        

        Then use it in the application entry:

        // app.js
        
        const apicache = require('apicache');
        
        const cache = apicache.middleware;
        
        
        
        // ... other code ...
        
        
        
        // Cache GET requests for 5 minutes
        
        app.use('/api', cache('5 minutes'));
        
        
        
        // ... other code ...
        
        

        Add request rate limiting

        Prevent API abuse:

        npm install express-rate-limit --save
        
        

        Then use it in the application entry:

        // app.js
        
        const rateLimit = require('express-rate-limit');
        
        
        
        // ... other code ...
        
        
        
        // Create rate limiting middleware
        
        const apiLimiter = rateLimit({
        
          windowMs: 15 * 60 * 1000, // 15分钟
        
          max: 100, // 每个IP在windowMs时间内最多100个请求
        
          message: '来自此IP的请求过多,请稍后再试'
        
        });
        
        
        
        // Apply rate limiting middleware
        
        app.use('/api', apiLimiter);
        
        
        
        // ... other code ...