溫馨提示×

ubuntu swagger測試方法有哪些

小樊
45
2025-06-11 00:10:10
欄目: 智能運維

在Ubuntu上測試Swagger(現稱為OpenAPI)主要涉及安裝和配置Swagger UI和Swagger Editor,然后通過這些工具進行API文檔的生成和測試。以下是詳細的步驟和方法:

安裝Swagger UI和Swagger Editor

  1. 安裝Node.js和npm

    sudo apt update
    sudo apt install -y nodejs npm
    
  2. 安裝Swagger Editor

    sudo npm install -g swagger-editor
    

    啟動Swagger Editor:

    swagger-editor
    

    這將在默認瀏覽器中打開Swagger Editor界面。

  3. 安裝Swagger UI

    sudo npm install -g swagger-ui-express
    

    創建一個簡單的Express應用來托管Swagger UI:

    mkdir swagger-ui-example
    cd swagger-ui-example
    npm init -y
    npm install express
    

    創建一個名為 server.js 的文件,并添加以下內容:

    const express = require('express');
    const swaggerUi = require('swagger-ui-express');
    const YAML = require('yamljs');
    
    // Load Swagger document
    const swaggerDocument = YAML.load('./swagger.yaml');
    
    const app = express();
    
    // Serve Swagger docs
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
    

    創建一個名為 swagger.yaml 的文件,并添加你的Swagger文檔。

    啟動服務器:

    node server.js
    

    在瀏覽器中訪問 http://localhost:3000/api-docs 來查看Swagger UI。

使用Swagger進行API測試

  1. 訪問Swagger UI: 在瀏覽器中訪問 http://your_server_ip:3000/api-docs 來查看和測試API文檔。

  2. 使用Swagger Editor: 啟動Swagger Editor后,訪問 http://localhost:8080,使用你保存的Swagger YAML文件進行API文檔的編輯和查看。

  3. 集成Spring Boot項目: 在Spring Boot項目中集成Swagger,使用Springfox庫來自動化生成API文檔。

    • 添加Springfox依賴:

      <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
      </dependency>
      <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
      </dependency>
      
    • 配置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.basePackage("com.example.demo.controller"))
            .paths(PathSelectors.any())
            .build();
        }
      }
      
    • 訪問Swagger UI: 啟動Spring Boot應用后,在瀏覽器中訪問 http://localhost:8080/swagger-ui/,然后輸入配置文件中指定的Swagger JSON文件地址。

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

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