前端 Express 框架 Swagger 多接口定义及自动生成文档
在前端 Express 框架中使用 Swagger 时,可以定义多个 API 接口。Swagger 支持在一个文件中定义多个接口,只需要在 paths 对象中添加多个请求路径即可。
例如:
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "My API"
},
"host": "localhost:3000",
"basePath": "/api",
"schemes": [
"http"
],
"paths": {
"/users": {
"get": {
"summary": "Get all users",
"responses": {
"200": {
"description": "OK"
}
}
},
"post": {
"summary": "Create a new user",
"responses": {
"201": {
"description": "Created"
}
}
}
},
"/users/{id}": {
"get": {
"summary": "Get a user by ID",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "OK"
}
}
},
"put": {
"summary": "Update a user by ID",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "OK"
}
}
},
"delete": {
"summary": "Delete a user by ID",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"type": "integer"
}
],
"responses": {
"204": {
"description": "No Content"
}
}
}
}
}
}
在这个例子中,我们定义了两个请求路径,一个是/users,另一个是/users/{id},每个请求路径下又定义了不同的HTTP方法(get、post、put、delete)。
此外,Swagger 还提供了自动生成 API 文档的工具,例如 Swagger Editor 和 Swagger UI。你可以将你的 Swagger 定义文件导入到这些工具中,就可以方便地查看和测试 API 接口了。
原文地址: https://www.cveoy.top/t/topic/lExm 著作权归作者所有。请勿转载和采集!