在Ubuntu上配置和使用Swagger(现称OpenAPI)在微服务架构中可以帮助开发者自动化生成API文档、测试API接口,并促进团队协作。以下是详细的步骤和应用方法:
sudo apt update
sudo apt install nodejs npm
sudo npm install -g swagger-ui-express
mkdir swagger-ui-example
cd swagger-ui-example
npm init -y
npm install express
server.js
文件并添加以下内容:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// Load Swagger document
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
// Serve Swagger docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
创建swagger.yaml
文件并添加你的Swagger文档。
启动服务器:
node server.js
现在,你可以在浏览器中访问 http://localhost:3000/api-docs
来查看Swagger UI。
wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.50.0.tar.gz
tar -xvf v3.50.0.tar.gz
rm v3.50.0.tar.gz
cd swagger-editor-3.50.0
./bin/swagger-editor.sh
默认情况下,Swagger Editor可以通过 http://127.0.0.1:8080
访问。
pom.xml
中添加:<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.8.0</version>
</dependency>
@OpenApi
注解定义API的基本信息:@OpenApi(
info = @Info(title = "微服务API", version = "1.0.0", description = "这是一个微服务API的示例")
)
application.properties
或application.yml
中配置Swagger的相关参数:springdoc:
openapi:
version: 1.0.0
info:
title: 微服务API
version: 1.0.0
description: 这是一个微服务API的示例
@EnableOpenAPI
注解:@SpringBootApplication
@EnableOpenAPI
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
/swagger-ui/index.html
,即可看到生成的API文档。npm install express swagger-ui-express swagger-jsdoc
swagger.config.js
:const options = {
definition: {
openapi: '3.0.0',
info: {
title: '微服务API',
version: '1.0.0',
},
},
apis: ['./routes/*.js'], // 包含API注释的文件路径
};
const specs = swaggerJsdoc(options);
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
通过以上步骤,你可以在Ubuntu系统中成功安装和配置Swagger UI和Swagger Editor,从而方便地设计和测试RESTful API。
API网关集成: 在API网关(如Kong, Nginx)层面统一集成Swagger UI,聚合所有微服务的API文档。
安全配置: 在生产环境中,通过环境变量控制Swagger的启用/禁用,并使用基本认证保护Swagger端点。
生产环境配置建议:
@Profile("dev")
限定只在开发环境启用。通过这些步骤和最佳实践,你可以在Ubuntu微服务架构中有效地应用Swagger,提高开发效率和API文档管理的质量。