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文档。