温馨提示×

Ubuntu Swagger如何进行API管理

小樊
57
2025-08-27 10:40:17
栏目: 智能运维

在Ubuntu上进行Swagger API管理,可参考以下步骤:

安装Swagger工具

基于Debian的Ubuntu系统,可更新包列表后安装swagger-jsdocswagger-ui-express。命令为:sudo apt updatesudo apt install swagger-jsdoc swagger-ui-express

创建API规范文件

用YAML或JSON格式创建swagger.yamlswagger.json文件,定义API的端点、参数等信息。例如:

swagger: '2.0'
info:
  version: 1.0.0
  title: Sample API
paths:
  /users:
    get:
      summary: List all users
      responses:
        200:
          description: An array of users

集成Swagger到应用

以Express框架为例,安装相关依赖后,在应用中引入Swagger UI并配置。代码如下:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
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}`);
});

实现版本控制

可在OpenAPI规范文件中,通过路径或操作ID包含版本号,如/v1/users,也可在服务器配置中设置不同路径前缀区分版本。还可使用Git等工具对Swagger定义文件进行版本管理,通过分支管理不同版本的API。

部署与测试

运行应用后,访问http://localhost:3000/api-docs(端口可根据配置修改),可查看和测试API。

0