在Linux下,使用Swagger生成交互式API文档通常涉及以下步骤:
安装Swagger工具:
npm install -g swagger-jsdoc
编写API规范:
swagger.yaml
的文件,并填写你的API信息。生成文档:
swagger-jsdoc
工具从你的API规范文件生成文档。swagger-jsdoc -c path/to/swagger.yaml
使用Swagger UI:
npm install swagger-ui-express
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./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文档。假设你有一个简单的Express应用,并且你已经安装了必要的依赖项。以下是一个完整的示例:
安装依赖项:
npm install express swagger-jsdoc swagger-ui-express
创建Swagger规范文件(swagger.yaml
):
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
创建Express应用(app.js
):
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.yaml');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
运行应用:
node app.js
访问文档:
http://localhost:3000/api-docs
,你应该能够看到交互式的API文档。通过这些步骤,你可以在Linux环境下使用Swagger生成和查看交互式API文档。