網站首頁 編程語言 正文
需要轉換的接口
現在我需要轉換的接口全是nodejs寫的數據,而且均為post傳輸的json格式接口
apiDoc格式
apiDoc代碼中的格式如下:
/**
* @api {方法} 路徑 標題
* @apiGroup Group
* @apiDescription 描述這個API的信息
*
* @apiParam {String} userName 用戶名
* @apiParamExample {json} request-example
* {
* "userName": "Eve"
* }
*
* @apiError {String} message 錯誤信息
* @apiErrorExample {json} error-example
* {
* "message": "用戶名不存在"
* }
*
*
* @apiSuccess {String} userName 用戶名
* @apiSuccess {String} createTime 創建時間
* @apiSuccess {String} updateTime 更新時間
* @apiSuccessExample {json} success-example
* {
* "userName": "Eve",
* "createTime": "1568901681"
* "updateTime": "1568901681"
* }
*/function getUserInfo(username) {
// 假如這個函數是根據用戶名返回用戶信息的
}
使用npm安裝apidoc插件:
npm install apidoc
再新建對應的apidoc.json,格式如下:
{ "name": "文檔名", "version": "版本號", "description": "解釋", "title": "標題", "url" : "地址" }
然后在apidoc.json路徑下執行命令可以生成接口文檔(src是接口代碼文件夾,apidoc是生成文檔的文件夾):
apidoc -i src/ -o apidoc/
生成后可以在apidoc文件夾中打開index.html查看生成的接口文檔,生成文檔時會生成一個api_data.json,下面會用到
swagger格式
這里我們暫時只需要關注參數為json的接口格式
{ "swagger": "2.0", "info": { "description": "1.0版本接口文檔", "version": "1.0.5", "title": "智能醫療輔助平臺", "termsOfService": "http://swagger.io/terms/" }, "host": "http://localhost:8080", "basePath": "/", "tags": [], "paths": {}, "definitions": {} }
其中path是存放接口的,tags是存放的分組名列表,definitions是實體列表(json參數)
思路
使用apidoc包生成apidoc的json格式數據,然后使用python讀取出接口地址、名字、組名、輸入參數格式和例子、輸出參數格式和例子等,然后根據swagger格式填入對應的數據即可生成swagger的json格式
我的話是會直接使用處理出的swagger的json格式的數據導入yApi中
代碼
代碼雖然在下面,但是是我臨時著急用寫的,有的地方是寫死的,需要改,這里放出來主要是講個大致的思路
import re
import json
import demjson
import decimal
# 保存時會出現byte格式問題,使用這個處理
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return float(o)
super(DecimalEncoder, self).default(o)
# 分析例子轉json,在這里可以自己添加規則
def analyze_demjson(json_data):
item = json_data.replace("\\n", "").replace("\\", "").replace(" ", "")
result_item = {}
try:
result_item = demjson.decode(item, encoding='UTF-8')
except:
print(item)
return result_item
# 獲取解析apidoc數據
def get_api_doc_data(name):
data_list = None
group_list = {}
with open(name, mode='r', encoding="UTF-8") as f:
data_list = json.load(f)
for data in data_list:
if data['group'] in group_list:
group_list[data['group']].append(data)
else:
group_list[data['group']] = [data]
return group_list
# 轉為swagger寫入
def set_swagger_data(data):
swagger_json = {
"swagger": "2.0",
"info": {
"description": "1.0版本接口文檔",
"version": "1.0.5",
"title": "智能醫療輔助平臺",
"termsOfService": "http://swagger.io/terms/"
},
"host": "http://localhost:8080",
"basePath": "/",
"tags": [],
"paths": {},
"definitions": {}
}
# 添加分組
for group_key in data:
swagger_json['tags'].append({
"name": group_key,
"description": group_key
})
# 添加接口信息
# 循環分組
for group_key in data:
# 循環每組列表
for interface in data[group_key]:
parameters = {}
if 'parameter' in interface and 'fields' in interface['parameter']:
# 獲取參數demo信息
content = ""
if 'examples' in interface['parameter']:
content = analyze_demjson(interface['parameter']['examples'][0]['content'])
# 添加參數信息
parameter_dict = {}
for parameter in interface['parameter']['fields']['Parameter']:
parameter_type = "None"
if "type" in parameter:
parameter_type = parameter['type'].lower()
if parameter_type == 'number':
parameter_type = "integer"
parameter_item = {
"description": parameter['description'].replace('<p>', '').replace('</p>', ''),
"required": parameter['optional'],
"type": parameter_type,
"default": ''
}
if parameter['field'] in content:
parameter_item['default'] = content[parameter['field']]
parameter_dict[parameter['field']] = parameter_item
parameters = {
"in": "body",
"name": interface['name'],
"description": interface['name'],
"required": "true",
"schema": {
"originalRef": interface['name'],
"$ref": "#/definitions/" + interface['name']
}
}
swagger_json['definitions'][interface['name']] = {
"type": "object",
"properties": parameter_dict
}
# 添加返回信息
responses = {
"200": {
"description": "successful operation",
"schema": {
"originalRef": interface['name'] + "_response",
"$ref": "#/definitions/" + interface['name'] + "_response"
}
}
}
schema = {
"type": "object",
"properties": {
"errcode": {
"type": "integer",
"default": 0,
"description": "編碼,成功返回1"
},
"data": {
"type": "object",
"default": {},
"description": "監管對象明細,包含表頭和數據內容兩部分"
},
"errmsg": {
"type": "string",
"default": "ok",
"description": '編碼提示信息,成功時返回 "ok"'
}
}
}
# 返回例子
if "success" in interface:
response_example = ""
if len(interface['success']['examples']) == 1:
response_example = analyze_demjson(interface['success']['examples'][0]['content'])
else:
response_example = analyze_demjson(interface['success']['examples']['content'])
if 'data' in response_example and response_example['data'] != {}:
schema['properties']['data'] = response_example['data']
swagger_json['definitions'][interface['name'] + "_response"] = schema
# 加入
swagger_json['paths'][interface['url']] = {
interface['type']: {
"tags": [group_key],
"summary": interface['title'].replace(interface['url'] + '-', ''),
"description": interface['title'],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [parameters],
"responses": responses
}}
# 寫入json文件
with open('swagger_data.json', 'w', encoding="UTF-8") as json_file:
json.dump(swagger_json, json_file, cls=DecimalEncoder, indent=4, ensure_ascii=False)
if __name__ == '__main__':
group_data = get_api_doc_data('api_data.json')
set_swagger_data(group_data)
原文鏈接:https://www.cnblogs.com/baby7/p/python_apidoc_to_swagger.html
相關推薦
- 2022-10-08 ASP.NET泛型三之使用協變和逆變實現類型轉換_實用技巧
- 2023-01-17 如何使用python中的networkx來生成一個圖_python
- 2023-03-23 python調用excel_vba的兩種實現方式_python
- 2024-02-29 UNI-APP頁面跳轉時(uni.navigateTo),參數傳遞
- 2022-08-20 在?pytorch?中實現計算圖和自動求導_python
- 2022-02-17 npm run serve Syntax Error: Error: Node Sass versi
- 2022-01-16 DOM簡介及獲取元素方法屬性總結
- 2022-03-08 C#中BackgroundWorker類用法總結_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支