python解析swagger文档数据

发布时间 2023-08-01 11:28:49作者: 牧羊人の冬天

众所周知swagger文档存储在api-docs接口中
可以通过http获取接口的响应或者直接copy json的响应到文本中,最终得到的数据都是data
处理逻辑如下:
with open("1.txt",'r',encoding='utf8') as f:
data = f.read()
data = json.loads(data)
basePath = data['basePath']
paths = data["paths"]

cases_data = []
for path, methods in paths.items():
    for method, details in methods.items():
        method = method.upper()
        summary = details["summary"]
        parameters = details.get("parameters", [])

        # 获取headers
        headers = {param['name']:"" for param in parameters if param.get("in") == "header"}

        # 获取body
        rep_body = [param.get('schema').get('originalRef') for param in parameters if param.get("in") == "body"]

        body = ''
        if rep_body:
            dto = data["definitions"].get(rep_body[0])
            if dto:
                properties = dto.get('properties')
                body = properties.copy()
                for item,params in properties.items():
                    for param,value in params.items():
                        if param == 'items':
                            new_dto = data["definitions"].get(value['originalRef'])
                            n_list = [{param:""} for param in new_dto['properties']]
                            body[item]=n_list
                        else:
                            body[item]= ''
        # 组装参数
        cases_data.append({
            "url": basePath+path,
            "method": method,
            "name": summary,
            "headers": headers,
            "body": body
        })
        print("Path:", basePath+path)
        print("Method:", method)
        print("Name",summary)
        print("Headers:")
        print(headers)
        print("Body:")
        print(body)
        print("-" * 30)


最终处理后的数据格式如下:
Path: /trr/creditResult
Method: POST
Name 接
状态
Headers:
{'x-user-token': '', 'x-req-timestamp': '', 'x-req-rd': ''}
Body:

Path: /t/withdrawalResult
Method: POST
Name 接

Headers:
{'x-user-token': '', 'x-req-timestamp': '', 'x-req-rd': ''}
Body: