溫馨提示×

Swagger在Ubuntu上的使用技巧

小樊
56
2025-04-01 09:53:55
欄目: 智能運維

Swagger是一款RESTful接口的文檔在線自動生成及功能測試工具,它可以幫助開發者規范化、標準化接口文檔,并支持接口的聯調和測試。以下是在Ubuntu上使用Swagger的一些技巧和步驟:

安裝Swagger UI

  1. 安裝Node.js和npm
  • 訪問Node.js官網下載并解壓Node.js。
  • 設置Node.js和npm的全局路徑:
    sudo ln -s /path/to/node-v16.15.1-linux-x64/bin/node /usr/local/bin/node
    sudo ln -s /path/to/node-v16.15.1-linux-x64/bin/npm /usr/local/bin/npm
    
  • 檢測安裝是否成功:
    node -v
    npm -v
    
  1. 安裝Express和其他必要的模塊
  • 安裝Express框架:
    npm install express --save
    
  • 安裝其他中間件,如body-parser、cookie-parser和multer:
    npm install body-parser cookie-parser multer --save
    
  1. 部署Swagger UI
  • 創建一個新的項目文件夾,例如node_app,并進入該文件夾。
  • 初始化項目并安裝所需的依賴:
    npm init -y
    npm install express --save
    
  • 復制Swagger UI的dist文件夾中的文件到項目的public文件夾中。
  • 修改index.js文件,設置靜態文件目錄并啟動服務器:
    var express = require('express');
    var app = express();
    app.use('/swagger', express.static('public'));
    app.get('/', function (req, res) { res.send('Hello World'); });
    app.listen(3000, function () {
      console.log("Swagger UI started on port 3000");
    });
    
  • 啟動服務器并訪問Swagger UI:
    node index.js
    
  • 在瀏覽器中訪問http://your-server-ip:3000/swagger即可看到Swagger UI。

在Spring Boot項目中集成Swagger

  1. 引入Swagger依賴

pom.xml中添加以下依賴:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>
  1. 配置Swagger

創建一個配置類,使用@Configuration@EnableSwagger2注解來啟用Swagger:

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}
  1. 使用Swagger注解

在Controller中使用Swagger注解來描述API接口,例如:

import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @ApiOperation(value = "Get user by ID", notes = "Returns a user based on the ID provided")
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable("id") Long id) {
        // 實現獲取用戶的邏輯
        return new User(id, "John Doe");
    }
}

通過以上步驟,你可以在Ubuntu上成功安裝和配置Swagger,從而方便地進行API文檔的生成和測試。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女