溫馨提示×

Swagger與Ubuntu如何協同工作

小樊
45
2025-05-05 13:50:01
欄目: 智能運維

Swagger與Ubuntu可以協同工作,主要用于API文檔的生成和測試。Swagger是一個工具集,包括Swagger Editor和Swagger UI,它們可以幫助開發者設計、構建、文檔化和使用RESTful web服務。Ubuntu是一個流行的Linux發行版,提供了穩定的環境和豐富的軟件包管理工具。

在Ubuntu上安裝Swagger

使用npm安裝Swagger UI

  1. 安裝Node.js和npm
sudo apt update
sudo apt install -y nodejs npm
  1. 下載并安裝Swagger UI
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.48.0.tar.gztar -xvf v3.48.0.tar.gz
cd swagger-ui-3.48.0
npm install
npm install -g http-server
http-server -p 8081

之后可以在瀏覽器中訪問 http://localhost:8081 來使用Swagger UI。

使用Docker安裝Swagger

  1. 安裝Docker
sudo apt update
sudo apt install docker.io
  1. 拉取Swagger UI Docker鏡像
docker pull swaggerapi/swagger-ui-express
  1. 運行Swagger UI容器
docker run -p 8080:8080 swaggerapi/swagger-ui-express

之后可以在瀏覽器中訪問 http://localhost:8080 來使用Swagger UI。

在Ubuntu上集成Swagger與Spring Boot項目

  1. 創建Spring Boot項目: 使用Spring Initializr創建一個新的Spring Boot項目,并添加Spring Web和Springfox Swagger2依賴。

  2. 添加Swagger依賴: 在pom.xml文件中添加以下依賴:

<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>
  1. 配置Swagger: 創建一個配置類來啟用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();
    }
}
  1. 運行Spring Boot應用: 在終端中運行以下命令來啟動Spring Boot應用:
./mvnw spring-boot:run
  1. 訪問Swagger UI: 打開瀏覽器并訪問 http://localhost:8080/swagger-ui.html,你應該能夠看到你的API文檔和測試界面。

通過以上步驟,你可以在Ubuntu上成功地將Swagger集成到Spring Boot項目中,并進行API文檔的生成和測試。

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