在Ubuntu系統上使用Swagger測試API通常涉及以下幾個步驟:
首先,需要在Ubuntu系統上安裝Node.js和npm??梢酝ㄟ^以下命令安裝:
sudo apt update
sudo apt install -y nodejs npm
驗證安裝是否成功:
node -v
npm -v
有幾種方法可以在Ubuntu上安裝Swagger UI:
git clone https://github.com/swagger-api/swagger-ui.git
cd swagger-ui
npm install
npm start
然后,在瀏覽器中訪問 http://localhost:3000/swagger-ui/index.html
即可看到Swagger UI界面。
sudo npm install -g http-server
解壓Swagger UI的源碼包(可以從Swagger官網下載),并將解壓后的 dist
目錄中的文件復制到Swagger UI源碼目錄中的 public
文件夾。接著,運行以下命令啟動http-server:
http-server -p 8080
在瀏覽器中訪問 http://localhost:8080
即可看到Swagger UI界面。
如果你的后端服務是基于Spring Boot的,可以使用 springfox-swagger2
和 springfox-swagger-ui
來集成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>
然后,創建一個配置類來啟用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();
}
}
啟動Spring Boot應用后,訪問 http://localhost:8080/swagger-ui.html
即可看到Swagger UI界面,其中展示了項目中定義的所有API接口及其詳細信息。
在Swagger UI界面中,可以找到你定義的API接口,點擊相應的接口,然后點擊“Try it out”按鈕即可測試API。你可以在“Params”部分輸入參數,在“Body”部分輸入請求體(如果是POST請求),然后點擊“Execute”按鈕執行請求并查看響應結果。
請注意,具體的安裝步驟可能會根據Linux發行版和Swagger版本的不同而有所差異。建議參考官方文檔或相關的教程來獲取詳細的安裝指南。