Swagger(現在通常稱為OpenAPI)可以在Ubuntu上集成,以下是幾種集成方法:
sudo apt update
sudo apt install nodejs npm
mkdir swagger-demo
cd swagger-demo
npm init -y
npm install swagger-ui-express
創建一個名為 app.js 的文件,并添加以下代碼:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// 讀取Swagger文檔
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
// 將Swagger文檔添加到Express應用中
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 啟動服務器
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
在項目目錄中創建一個名為 swagger.yaml 的文件,并添加你的API的Swagger規范。例如:
swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger UI on Ubuntu
version: '1.0.0'
host: localhost:3000
basePath: /
schemes:
- http
paths:
/users:
get:
summary: List all users
responses:
200:
description: An array of users
node app.js
現在,你可以在瀏覽器中訪問 http://localhost:3000/api-docs 來查看Swagger UI界面,并與你的API進行交互。
sudo apt update
sudo apt install docker.io
docker pull swaggerapi/swagger-ui-express
docker run -p 8080:8080 swaggerapi/swagger-ui-express
打開瀏覽器并訪問 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>
創建一個Java類來配置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();
}
}
啟動Spring Boot項目后,訪問 http://localhost:8080/swagger-ui.html(假設服務端口為8080),可以看到Swagger UI界面。
通過以上步驟,你可以在Ubuntu上成功集成Swagger,并查看和測試你的API文檔。