前端 Express 框架 Swagger 多接口配置 - 如何定义不同路径 API 接口
Swagger 并不要求将不同请求路径的 API 接口放在不同的文件中,但为了更好的组织和管理,可以将它们分别写在不同的文件中。
在编写 Swagger 时,可以使用'paths' 字段来定义 API 的请求路径和方法,例如:
{
"paths": {
"/api/users": {
"get": {
"description": "Get a list of all users",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
}
},
"post": {
"description": "Create a new user",
"parameters": [
{
"name": "user",
"in": "body",
"description": "User object",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/User"
}
}
}
}
},
"/api/users/{id}": {
"get": {
"description": "Get a specific user",
"parameters": [
{
"name": "id",
"in": "path",
"description": "User ID",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/User"
}
}
}
}
}
}
}
在上面的例子中,我们定义了两个 API 接口,一个是获取所有用户的接口,另一个是获取指定用户的接口,它们分别对应不同的请求路径。
除了'paths' 字段之外,还可以使用'definitions' 字段来定义数据模型,'parameters' 字段来定义请求参数,'responses' 字段来定义响应结果等等。
至于 Swagger 是否有自动生成的功能,答案是肯定的。Swagger 提供了许多工具和插件,可以根据代码自动生成 API 文档和客户端代码。常用的工具包括 Swagger UI、Swagger Codegen 等。
原文地址: https://www.cveoy.top/t/topic/lExl 著作权归作者所有。请勿转载和采集!