Web application framework Express builds RESTful API

Express framework

Express is one of the most commonly used web application frameworks on the Node.js platform, it is clean, flexible and easy to use. Express provides a powerful set of features and tools that help developers quickly build web applications and RESTful APIs.

Here are some key features and capabilities of the Express framework:

  1. Lightweight: Express is a lightweight framework that provides the most basic functions and tools without excessive redundant code. This makes Express easy to use and free to choose and integrate other middleware and plugins.

  2. Express routing: Express provides a flexible routing function, which can define routing handlers according to different request paths and HTTP methods. This makes it easy to map requests to corresponding processing logic.

  3. Middleware support: Express' powerful middleware support is one of its biggest features. Middleware is a function that can handle between request and response, and multiple middleware can be chained as needed. Developers can use existing middleware or custom middleware to implement various functions, such as authentication, logging, error handling, etc.

  4. View Engines: Express allows various view engines to render dynamic content such as EJS, Handlebars, etc. The view engine can combine data and templates to generate the final HTML page, which is convenient for developers to build dynamic Web applications.

  5. Serving static files: Express provides an easy way to serve static files such as images, CSS, and JavaScript. In this way, developers can directly access these static resources without additional routing settings.

  6. RESTful API support: Express is very friendly for building RESTful APIs. Through reasonable design of routing and middleware, API interfaces conforming to RESTful style can be quickly constructed.

  7. Active community: Express has a large and active development community, and there are a large number of plug-ins and middleware to choose from. This means that developers can get a lot of useful resources and support from the community.

Web applications can be quickly built using Express, one of the most popular and widely used web frameworks in the Node.js ecosystem. Whether developing a simple website or a complex web application, Express is an excellent framework to choose.

Example of building a backend API with Express

When using the Express framework to build a backend that requests API, connects to MySQL, and generates API documentation, it needs to be divided into the following steps:

  1. Install dependencies: First, you need to make sure your Node.js environment is installed, and run the following command in the project root directory to install the required dependencies:
npm install express mysql body-parser swagger-jsdoc swagger-ui-express
  1. Create an Express app: Create an Express app and set up routing, connect to a database, and more.
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const swaggerJSDoc = require('swagger-jsdoc');
const swaggerUI = require('swagger-ui-express');

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

// 解析请求体
app.use(bodyParser.json());

// 连接 MySQL 数据库
const db = mysql.createConnection({
    
    
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name',
});

db.connect((err) => {
    
    
  if (err) {
    
    
    console.error('Database connection failed: ', err);
  } else {
    
    
    console.log('Connected to the database');
  }
});

// 示例 API 路由
app.get('/api/data', (req, res) => {
    
    
  db.query('SELECT * FROM data_table', (err, results) => {
    
    
    if (err) {
    
    
      console.error('Error querying database: ', err);
      res.status(500).send('Internal Server Error');
    } else {
    
    
      res.json(results);
    }
  });
});

// 生成 Swagger 文档配置
const swaggerOptions = {
    
    
  definition: {
    
    
    openapi: '3.0.0',
    info: {
    
    
      title: 'API Documentation',
      version: '1.0.0',
    },
  },
  apis: ['./app.js'], // 指定包含 API 路由的文件
};

const swaggerSpec = swaggerJSDoc(swaggerOptions);
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerSpec));

app.listen(port, () => {
    
    
  console.log(`Server is running on port ${
      
      port}`);
});
  1. Generate API doc comments: In your Express app code, add Swagger doc comments for each route.
/**
 * @swagger
 * /api/data:
 *   get:
 *     summary: Get data from the database
 *     responses:
 *       200:
 *         description: Successful response with data
 *         content:
 *           application/json:
 *             example:
 *               - id: 1
 *                 name: Example Data
 */
  1. Run the application: Run the following command in the project root directory to start the Express application:
node app.js
  1. Access API Documentation: Visit in your browser http://localhost:3000/api-docsand you will be able to see the generated Swagger API documentation.

The above code example is just a basic Express application, you can extend and customize it according to your needs. At the same time, you need to replace the database connection information and example routes and data tables, etc. Also, to better organize your code, you may want to split your routing and database operations into different modules.

Express project structure

For a large Express project, reasonable directory structure division can help improve code maintainability and scalability. The following is a common example of an optimal directory structure:

project/
  ├── app/
  │    ├── controllers/
  │    ├── models/
  │    ├── routes/
  │    ├── middlewares/
  │    ├── services/
  │    └── utils/
  ├── config/
  │    ├── env/
  │    └── config.js
  ├── public/
  │    ├── css/
  │    ├── js/
  │    └── images/
  ├── views/
  ├── tests/
  ├── app.js
  ├── package.json
  └── README.md

Explanation of the meaning of the directory structure:

  1. app/: store the core code of the application.

    • controllers/: Controller, used to handle requests and responses.
    • models/: Data model, used to define database models and operations.
    • routes/: Routing, used to define each routing and request processing logic.
    • middlewares/: Middleware for handling pre-request or post-response logic.
    • services/: Service layer, used to process business logic.
    • utils/: Tool function, used to store some commonly used tool functions.
  2. config/: Store the configuration file of the project.

    • env/: Configuration files for different environments, such as development environment, production environment, etc.
    • config.js: Common configuration files, such as database connection, port number, etc.
  3. public/: Store static resource files, such as CSS, JavaScript, pictures, etc.

  4. views/: store view files for rendering front-end pages.

  5. tests/: Store test codes for unit testing and integration testing of the project.

  6. app.js: The entry file of the application, which is responsible for starting the Express application and setting the middleware.

  7. package.json: The configuration file of the project, including information such as dependencies and scripts.

  8. README.md: The description document of the project, which is used to describe the function and usage of the project.

This directory structure clearly divides different functional modules, making the code organization more orderly and easier to maintain. At the same time, using configuration files to store environment-related configuration information can easily switch configurations in different environments, thereby improving the flexibility and configurability of the project.

Swagger API Documentation

Swagger API document (also called OpenAPI document) is a standardized specification describing RESTful API, which uses YAML or JSON format to define the structure, path, parameters, response and other related information of API. The goal of the Swagger API documentation is to provide a unified way to describe and share information about the API, making it easier for developers and teams to understand, use, and test the API.

Here are some core components and introductions from the Swagger API documentation:

  1. Basic information: The API documentation contains some basic information, such as the title, version, description, etc. of the API. This information helps other developers understand the basics of the API.

  2. Paths and operations: The different paths and operations (HTTP methods) provided by the API are listed in the documentation, along with details about each operation. For example, operations such as GET, POST, PUT, DELETE, etc.

  3. Request Parameters: For each operation, the API documentation describes the input parameters required for that operation. This includes query parameters, path parameters, request body parameters, etc.

  4. Response definition: The API document defines the response structure of each operation, including the HTTP status code, data type and structure of the response body.

  5. Error Responses: Documentation usually also lists the error responses that may be returned by the operation, including error codes, error messages, and error details.

  6. Data types and models: An API document can define various data types and models for the data structure of requests and responses. This can help developers better understand the format and structure of the data.

  7. Security and authorization: Swagger API documentation can define the security requirements and authorization mechanism of the API, as well as how to perform authentication and permission control.

  8. Samples and code: Documentation can provide sample requests and responses, as well as code samples in different programming languages, to help developers better understand how to use the API.

  9. API documentation tool: Using the Swagger tool, the API documentation can be rendered into an interactive Swagger UI, enabling developers to browse, test and debug the API intuitively.

In your API route handler file, you need to add Swagger annotations for each API to specify its actions and parameters. For example, here's how to add Swagger annotations for the "get all user info" API:

// routes/userRoutes.js

/**
 * @swagger
 * /api/users:
 *   get:
 *     summary: 获取所有用户信息
 *     description: 获取所有用户信息的API端点
 *     responses:
 *       200:
 *         description: 成功获取用户信息
 *       500:
 *         description: 服务器内部错误
 */
router.get('/', (req, res) => {
    
    
  // 在这里编写获取所有用户信息的逻辑
});

You need to add similar Swagger annotations for each API, including request method (GET, POST, PUT, DELETE), path, operation summary, operation description, and response information. Make sure to provide the correct information in the comments, based on your actual API implementation.
online debugging

In summary, the Swagger API documentation is a standardized specification for describing various aspects of a RESTful API. By using the Swagger tool, you can automatically generate an interactive API document interface based on the API document, making it easier for developers and teams to understand and use the API.

Guess you like

Origin blog.csdn.net/weixin_44008788/article/details/132499683