Swagger 多文件配置:使用 $ref 引入 JSON 文件和其他格式
对于 Swagger 多文件配置,可以使用 '$ref' 关键字来引用其他的 JSON 文件。例如,假设有一个 user.json 文件:
{
'type': 'object',
'properties': {
'id': {
'type': 'integer'
},
'name': {
'type': 'string'
}
}
}
然后可以在另一个主文件中使用 '$ref' 引用该文件:
{
'swagger': '2.0',
'info': {
'title': 'My API',
'version': '1.0.0'
},
'paths': {
'/users': {
'get': {
'summary': 'Get a list of users',
'responses': {
'200': {
'description': 'OK',
'schema': {
'$ref': 'user.json'
}
}
}
}
}
}
}
这样,Swagger 会自动读取 user.json 文件,并将其内容作为响应的 schema。
对于其他配置文件的格式,Swagger 支持多种格式,包括 YAML、XML 等。具体使用哪种格式取决于个人喜好和项目需求。在主文件中使用 '$ref' 引用其他文件时,只需指定文件的路径和文件名即可。例如:
{
'$ref': 'definitions.yaml#/User'
}
被引用的 JSON 文件示例
以下是一个简单的被引用的 JSON 文件示例:
{
'definitions': {
'User': {
'type': 'object',
'properties': {
'id': {
'type': 'integer'
},
'name': {
'type': 'string'
}
}
}
}
}
该文件定义了一个 User 对象,包括 id 和 name 两个属性。在主文件中使用 '$ref' 引用时,可以指定该文件的路径和文件名,例如:
{
'swagger': '2.0',
'info': {
'title': 'My API',
'version': '1.0.0'
},
'paths': {
'/users': {
'get': {
'summary': 'Get a list of users',
'responses': {
'200': {
'description': 'OK',
'schema': {
'$ref': 'user.json#/definitions/User'
}
}
}
}
}
}
}
这里使用了 user.json 文件中定义的 User 对象作为响应的 schema。注意,在 '$ref' 中需要指定被引用对象的路径,以及该对象在文件中的名称。
被引用的文件内容示例
被引用的文件通常包含一些公共的定义或者数据模型,供多个 API 接口使用。例如,一个定义了各种 HTTP 状态码的文件或者一个定义了用户数据模型的文件。这些文件通常都是以 JSON 或者 YAML 格式编写的,具体内容取决于文件的用途和项目需求。
以下是一个示例,定义了一个包含用户信息的数据模型:
{
'definitions': {
'User': {
'type': 'object',
'properties': {
'id': {
'type': 'integer'
},
'name': {
'type': 'string'
},
'email': {
'type': 'string',
'format': 'email'
}
},
'required': [
'id',
'name',
'email'
]
}
}
}
该文件中定义了一个 User 对象,包含 id、name 和 email 三个属性,其中 email 属性的格式必须符合 email 的规则。在使用 '$ref' 引用时,可以指定该文件的路径和文件名,例如:
{
'swagger': '2.0',
'info': {
'title': 'My API',
'version': '1.0.0'
},
'paths': {
'/users': {
'get': {
'summary': 'Get a list of users',
'responses': {
'200': {
'description': 'OK',
'schema': {
'$ref': 'user.json#/definitions/User'
}
}
}
}
}
}
}
这里使用了 user.json 文件中定义的 User 对象作为响应的 schema。注意,在 '$ref' 中需要指定被引用对象的路径,以及该对象在文件中的名称。
通过使用 '$ref' 关键字,可以有效地组织 Swagger 文档,提高代码的可读性和可维护性。
原文地址: https://www.cveoy.top/t/topic/lEBx 著作权归作者所有。请勿转载和采集!