在Linux上部署Swagger服務通常涉及以下幾個步驟:
安裝Swagger工具:
npm install -g swagger-jsdoc swagger-ui-express
準備Swagger配置文件:
swagger.json
或swagger.yaml
,用于描述你的API接口。swagger: '2.0'
info:
title: Sample API
description: API documentation for my sample application
version: '1.0.0'
host: api.example.com
basePath: /v1
schemes:
- https
paths:
/users:
get:
summary: List all users
responses:
'200':
description: An array of users
schema:
type: array
items:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
required:
- id
- name
創建Express應用:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
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}`);
});
運行Express應用:
node app.js
訪問Swagger UI:
http://<your-server-ip>:3000/api-docs
,你應該能夠看到Swagger UI界面,其中包含了你的API文檔。通過以上步驟,你就可以在Linux上成功部署Swagger服務,并通過Swagger UI來查看和測試你的API接口。