在Ubuntu上使用Swagger生成交互式API文档,通常涉及以下步骤:
安装Swagger工具:
sudo apt update
sudo apt install nodejs npm
swagger-jsdoc:sudo npm install -g swagger-jsdoc
编写API规范:
swagger.yaml的文件,并填写你的API信息。以下是一个简单的示例:openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
summary: List all users
responses:
'200':
description: An array 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
required:
- id
- name
生成API文档:
swagger-jsdoc工具从你的API规范文件生成文档。例如:swagger-jsdoc -c path/to/swagger.yaml -o ./path/to/output
使用Swagger UI:
swagger-ui-express(如果你使用的是Express框架):npm install swagger-ui-express
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./path/to/swagger.json'); // 这是你生成的Swagger文档
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
访问文档:
http://localhost:3000/api-docs来查看交互式的API文档。通过以上步骤,你可以在Ubuntu环境下使用Swagger生成和查看交互式API文档。