在Linux上利用Swagger進行API設計,通常涉及以下幾個步驟:
sudo apt update
sudo apt install -y nodejs npm
npm install -g swagger
或者下載Swagger Editor的Docker鏡像并在Linux上運行:
docker pull swaggerapi/swagger-editor
docker run -p 8080:8080 swaggerapi/swagger-editor
npm install -g swagger-ui
或者下載Swagger UI的源碼并在Linux上構建:
git clone https://github.com/swagger-api/swagger-ui.git
cd swagger-ui
npm install
npm run build
然后將構建好的文件復制到Web服務器的目錄中,例如/var/www/html。
swagger.yaml
文件:swagger: '2.0'
info:
version: 1.0.0
title: 測試Swagger文檔
description: 測試Swagger文檔API
contact:
name: 行百里者
url: https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI1MDU1MjkxOQ==
license:
name: MIT
url: http://opensource.org/licenses/MIT
schemes:
- http
host: traveler100.com
basePath: /api/v1
paths:
/user/{mobile}:
get:
summary: 根據手機號碼獲取一個用戶信息
description: 根據手機號碼獲取一個用戶信息
parameters:
- name: mobile
in: path
required: true
description: 手機號碼
schema:
type: string
responses:
'200':
description: OK
啟動Swagger:配置完成后,可以通過命令行啟動Swagger,或者在瀏覽器中訪問Swagger UI的配置URL來查看和使用Swagger。
測試API:在Swagger UI界面中,可以點擊“TRY IT OUT”按鈕來測試API請求,輸入必要的參數,然后發送請求并查看返回結果。
如果你使用的是Spring Boot項目,可以集成Swagger2來自動生成API文檔:
pom.xml
中添加Swagger2的依賴:<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>
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();
}
}
通過以上步驟,你可以在Linux上利用Swagger進行API設計,包括安裝、配置、使用Swagger Editor和Swagger UI,以及集成Spring Boot項目。Swagger提供了一個直觀的界面來生成和測試API文檔,從而簡化了API的開發和維護過程。