溫馨提示×

Swagger文檔Ubuntu如何生成

小樊
52
2025-04-01 09:48:54
欄目: 智能運維

在Ubuntu上生成Swagger文檔通常涉及以下幾個步驟:

1. 安裝Node.js和npm

首先,確保你的系統上已經安裝了Node.js和npm。你可以通過以下命令來安裝它們:

sudo apt update
sudo apt install nodejs npm

或者,你可以從Node.js官網下載并安裝最新版本的Node.js和npm。

2. 安裝Swagger UI

有幾種方法可以在Ubuntu上安裝Swagger UI:

方法一:從npm全局安裝http-server

sudo npm install -g http-server

然后,你可以通過以下命令在任意目錄啟動Swagger UI:

http-server

默認情況下,Swagger UI會在http://localhost:8080上運行。

方法二:從源碼安裝Swagger UI

你可以從Swagger UI的GitHub倉庫下載最新版本的Swagger UI源碼,然后解壓并在dist目錄下運行http-server。

git clone https://github.com/swagger-api/swagger-ui.git
cd swagger-ui
npm install
http-server dist

3. 配置Swagger

如果你正在使用Spring Boot項目,你可以使用springdoc來自動生成Swagger文檔。首先,添加springdoc-openapi-starter-webmvc-ui依賴到你的pom.xml文件中:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.1.0</version>
</dependency>

然后,在Spring Boot應用的主類上添加@EnableSwagger2注解:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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();
    }
}

4. 訪問Swagger文檔

啟動你的Spring Boot應用后,你可以通過以下URL訪問Swagger文檔:

http://localhost:8080/swagger-ui.html

如果你使用的是springdoc,則訪問:

http://localhost:8080/docs

5. 使用Swagger Editor(可選)

如果你需要更強大的API文檔編輯功能,可以安裝Swagger Editor。你可以從Swagger Editor的GitHub倉庫下載并安裝它。安裝完成后,你可以通過以下命令啟動Swagger Editor:

npm start

然后在瀏覽器中訪問http://localhost:9000來使用Swagger Editor編輯和查看你的API文檔。

以上就是在Ubuntu上生成Swagger文檔的基本步驟。希望這些信息對你有所幫助!

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