在Ubuntu上,Swagger(现在通常指的是OpenAPI)支持的主要格式是 JSON和YAML。以下是详细说明:
{
"swagger": "2.0",
"info": {
"title": "Sample API",
"description": "A sample API to demonstrate Swagger configuration",
"version": "1.0.0"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": [
"https"
],
"paths": {
"/users": {
"get": {
"summary": "List all users",
"description": "Returns a list of users",
"responses": {
"200": {
"description": "An array of users",
"schema": {
"type": "array",
"items": {
"ref": "#/definitions/User"
}
}
}
}
}
},
"/users/{userId}": {
"get": {
"summary": "Get a user by ID",
"description": "Returns a user based on the provided ID",
"parameters": [
{
"in": "path",
"name": "userId",
"type": "string",
"required": true
}
],
"responses": {
"200": {
"description": "A single user",
"schema": {
"ref": "#/definitions/User"
}
}
}
}
}
},
"definitions": {
"User": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"email": {
"type": "string"
}
}
}
}
}
- **YAML格式**:Swagger配置文件也可以使用YAML格式编写。例如,以下是一个简单的YAML格式的Swagger配置文件示例:
```yaml
swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger configuration
version: '1.0.0'
host: api.example.com
basePath: /v1
schemes:
- https
paths:
/users:
get:
summary: List all users
description: Returns a list of users
responses:
'200':
description: An array of users
schema:
type: array
items:
ref: '#/definitions/User'
/users/{userId}:
get:
summary: Get a user by ID
description: Returns a user based on the provided ID
parameters:
- in: path
name: userId
type: string
required: true
responses:
'200':
description: A single user
schema:
ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: string
name:
type: string
email:
type: string
安装Swagger工具:
使用npm(Node.js的包管理器)来安装Swagger命令行工具和Swagger UI。
sudo apt update
sudo apt install nodejs npm
npm install -g swagger-jsdoc swagger-ui-express
创建Swagger配置文件:
在你的项目根目录下创建一个名为 swagger.json 或 swagger.yaml 的文件,具体取决于你选择的格式。这个文件将包含你的API定义。
在应用程序中使用Swagger UI:
如果你正在使用Express.js作为你的Web框架,你可以使用 swagger-ui-express 中间件来集成Swagger UI。
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));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
通过这些步骤,你可以在Ubuntu上成功设置和使用Swagger,支持JSON和YAML格式的配置文件。