在Debian上测试Swagger API主要涉及安装和配置Swagger工具,然后通过Swagger UI进行API文档的查看和测试。以下是详细步骤:
首先,确保你的Debian系统已经更新到最新状态,并安装必要的软件包:
sudo apt update
sudo apt upgrade
sudo apt install -y nodejs npm
pip install flasgger
from flask import Flask
from flasgger import Swagger
app = Flask(__name__)
Swagger(app)
npm install swagger-ui-express swagger-jsdoc
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'My API',
version: '1.0.0',
},
},
apis: ['./routes/*.js'], // Path to the API docs
};
const swaggerDocs = swaggerJsDoc(options);
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在你的API代码中添加Swagger注解,以便Swagger工具能够生成详细的API文档。
from flasgger import swag_from
@app.route('/hello_world')
@swag_from('swagger.yaml')
def hello_world():
"""This is a simple hello world endpoint."""
return {'message': 'Hello, World!'}
/**
* @swagger
* /hello_world:
* get:
* summary: Returns a hello world message
* responses:
* '200':
* description: A successful response
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
*/
app.get('/hello_world', (req, res) => {
res.json({ message: 'Hello, World!' });
});
启动你的Debian项目后,访问Swagger UI界面,通常是 [http://your-debian-server-ip:port/swagger-ui/ 或 http://your-debian-server-ip:port/api-docs](http://your-debian-server-ip:port/swagger-ui/ 或 http://your-debian-server-ip:port/api-docs)。在Swagger UI界面中,你可以查看API文档,并进行交互式测试。
以上步骤可以帮助你在Debian系统上配置和使用Swagger进行API文档的查看和测试。