首页主机资讯如何编写ubuntu swagger API文档

如何编写ubuntu swagger API文档

时间2025-11-06 22:22:04发布访客分类主机资讯浏览461
导读:在Ubuntu上编写Swagger API文档的步骤 1. 准备基础环境 在Ubuntu系统上,首先需要安装Node.js和npm(Node.js包管理器),这是使用Swagger Editor、Swagger UI等工具的前提。打开终端,...

在Ubuntu上编写Swagger API文档的步骤

1. 准备基础环境

在Ubuntu系统上,首先需要安装Node.js和npm(Node.js包管理器),这是使用Swagger Editor、Swagger UI等工具的前提。打开终端,执行以下命令:

sudo apt update
sudo apt install -y nodejs npm

安装完成后,可通过nodejs -vnpm -v验证安装是否成功。

2. 安装Swagger核心工具

2.1 安装Swagger Editor(可视化编写规范)

Swagger Editor是Swagger生态中的在线/本地编辑工具,支持YAML/JSON格式的OpenAPI规范编写。通过npm全局安装:

sudo npm install -g swagger-editor-cli

安装完成后,启动本地编辑器实例:

swagger-editor-cli start

这会在默认浏览器中打开Swagger Editor(通常为http://localhost:8080),可直接在线编写或导入现有规范文件。

2.2 安装Swagger UI(可视化展示文档)

Swagger UI用于将OpenAPI规范转换为交互式网页文档,方便测试接口。若项目基于Node.js,可通过npm安装:

npm install -g swagger-ui-express

后续需结合Express框架集成到项目中(见步骤3)。

3. 编写OpenAPI规范文件

OpenAPI规范(OAS)是Swagger文档的基础,定义了API的端点、参数、响应、认证等信息。可通过以下两种方式创建:

3.1 使用Swagger Editor编写

打开Swagger Editor后,在左侧编辑区输入YAML格式的规范(示例如下),右侧会实时预览文档效果。完成后点击“Save”保存为swagger.yamlswagger.json文件。

openapi: 3.0.0
info:
  title: Sample API
  version: 1.0.0
  description: A simple API for demonstration
paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string

3.2 手动创建文件

使用文本编辑器(如vimnano)直接创建YAML文件,内容参考上述示例。保存至项目目录(如./docs/swagger.yaml)。

4. 集成Swagger UI到项目(可选,适用于Web应用)

若项目是基于Node.js的Web应用(如Express),可将Swagger UI集成到应用中,实现文档与应用的联动。示例如下:

4.1 安装依赖

npm install swagger-ui-express yamljs

4.2 编写集成代码

在Express应用的主文件(如app.js)中添加以下代码:

const express = require('express');
    
const swaggerUi = require('swagger-ui-express');
    
const YAML = require('yamljs');
    

const app = express();
    
// 读取OpenAPI规范文件
const swaggerDocument = YAML.load('./docs/swagger.yaml');
    
// 集成Swagger UI到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    

const PORT = process.env.PORT || 3000;
    
app.listen(PORT, () =>
 {

  console.log(`Server running at http://localhost:${
PORT}
    `);

  console.log(`Swagger UI available at http://localhost:${
PORT}
    /api-docs`);

}
    );

4.3 启动应用并访问文档

node app.js

打开浏览器访问http://localhost:3000/api-docs,即可看到交互式的Swagger文档,支持“Try it out”功能测试接口。

5. 自动化生成文档(可选,适用于代码优先的场景)

若已有后端代码(如Go、Java、Spring Boot),可使用工具从代码注释或注解自动生成OpenAPI规范,减少手动编写工作量。

5.1 Go语言(使用swag工具)

  • 安装swag
    go install github.com/swaggo/swag/cmd/swag@latest
    
  • 初始化swag:在项目根目录运行,生成docs目录及docs.go文件:
    swag init
    
  • 添加注释:在Controller文件中添加Swagger注释(示例如下):
    // @Summary Get user by ID
    // @Description Retrieve a user by their ID
    // @Tags Users
    // @Accept json
    // @Produce json
    // @Param id path int true "User ID"
    // @Success 200 {
    object}
     User
    // @Router /users/{
    id}
     [get]
    func GetUserByID(c *gin.Context) {
    
        // 业务逻辑
    }
        
    
  • 重新生成文档:修改代码后,再次运行swag initdocs目录下的swagger.yaml会自动更新。

5.2 Java/Spring Boot(使用Springfox)

  • 添加依赖:在pom.xml中添加Springfox依赖:
    <
        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>
    
    
  • 配置Swagger:创建配置类,启用Swagger并指定扫描包路径:
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    
        @Bean
        public Docket api() {
        
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                    .paths(PathSelectors.any())
                    .build()
                    .apiInfo(apiInfo());
    
        }
    
    
        private ApiInfo apiInfo() {
        
            return new ApiInfoBuilder()
                    .title("Spring Boot API")
                    .description("API Documentation")
                    .version("1.0")
                    .build();
    
        }
    
    }
    
    
  • 添加注解:在Controller中使用Swagger注解(示例如下):
    @Api(tags = "User Management")
    @RestController
    @RequestMapping("/users")
    public class UserController {
    
        @ApiOperation(value = "Get user by ID", notes = "Returns a single user")
        @GetMapping("/{
    id}
        ")
        public ResponseEntity<
        User>
     getUser(@PathVariable int id) {
        
            // 业务逻辑
            return ResponseEntity.ok(new User(id, "John Doe"));
    
        }
    
    }
        
    
  • 访问文档:启动Spring Boot应用,访问http://localhost:8080/swagger-ui.html即可查看文档。

6. 最佳实践建议

  • 遵循OpenAPI规范:使用YAML格式(更易读),遵循OAS 3.0标准,确保文档结构清晰。
  • 模块化管理:按功能模块划分API(如/users/products),使用tags分类,提高可维护性。
  • 版本控制:在info.version中指定API版本(如1.0.0),便于迭代管理。
  • 参数验证:明确参数的typerequiredformat(如int64string),避免歧义。
  • 自动化集成:将Swagger文档生成步骤集成到CI/CD流程(如Maven/Gradle插件、npm脚本),确保文档与代码同步。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 如何编写ubuntu swagger API文档
本文地址: https://pptw.com/jishu/744448.html
如何升级ubuntu上的swagger版本 如何测试ubuntu上的swagger API

游客 回复需填写必要信息