前端Express框架Swagger使用:多接口定义和引用
Swagger是一种API文档规范和工具,通常用于描述和可视化RESTful API。它允许您定义API的端点、参数、请求体、响应体等,以及生成API文档、客户端代码和服务器存根。
对于您遇到的问题,如果您的接口只有一种情况,您可以将其放在一个单独的JSON文件中,并使用Swagger UI或其他Swagger工具进行文档化和测试。
如果您需要编写多个接口,每个接口都有不同的请求路径和参数,您可以将它们放在不同的JSON文件中,并使用'$ref'关键字引用这些文件。例如,您可以在一个JSON文件中定义所有公共参数和响应,然后在其他文件中引用它们。
以下是一个示例,其中一个JSON文件定义了公共参数和响应,另一个JSON文件定义了一个特定的API端点:
common.json:
{
'parameters': {
'limit': {
'type': 'integer',
'description': 'The maximum number of items to return',
'default': 10
},
'offset': {
'type': 'integer',
'description': 'The number of items to skip',
'default': 0
}
},
'responses': {
'400': {
'description': 'Bad request',
'schema': {
'$ref': '#/definitions/Error'
}
},
'401': {
'description': 'Unauthorized',
'schema': {
'$ref': '#/definitions/Error'
}
}
}
}
api.json:
{
'swagger': '2.0',
'info': {
'version': '1.0.0',
'title': 'My API'
},
'paths': {
'/users': {
'get': {
'summary': 'Get a list of users',
'parameters': [
{
'$ref': 'common.json#/parameters/limit'
},
{
'$ref': 'common.json#/parameters/offset'
}
],
'responses': {
'200': {
'description': 'OK',
'schema': {
'type': 'array',
'items': {
'$ref': '#/definitions/User'
}
}
},
'$ref': 'common.json#/responses/400',
'$ref': 'common.json#/responses/401'
}
}
}
},
'definitions': {
'User': {
'type': 'object',
'properties': {
'id': {
'type': 'integer'
},
'name': {
'type': 'string'
}
}
},
'Error': {
'type': 'object',
'properties': {
'code': {
'type': 'integer'
},
'message': {
'type': 'string'
}
}
}
}
}
在此示例中,common.json定义了公共参数和响应,api.json定义了一个特定的API端点,并引用了common.json中的参数和响应。您可以按照类似的方式定义更多的JSON文件,并在需要时引用它们。
希望这可以帮助您开始使用Swagger来描述和文档化您的API。
原文地址: http://www.cveoy.top/t/topic/lExQ 著作权归作者所有。请勿转载和采集!