Guest User

Untitled

a guest
Nov 17th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.02 KB | None | 0 0
  1. # Generates Markdown for Confluence Wiki from a given Collection file exported from Postman per Collections 2.1 schema
  2. # Change working_dir and input_file to suit, then run it
  3.  
  4. import json
  5. from operator import itemgetter
  6. from itertools import groupby
  7.  
  8.  
  9. # A postman collection, in Postman 2.1 format
  10. working_dir = "C:\Users\Sreedhar\Documents\TCS Projects\NM\API Documentation"
  11. input_file = working_dir + "\NMVIP.json"
  12. serial_num = 1
  13.  
  14. def clean(s):
  15. s = (str(s).decode('string_escape'))
  16. s = s.replace('{{', '$').replace('}}', '').replace('\r\n', '')
  17. return s[1:-1]
  18.  
  19.  
  20. def clean_list(a_list):
  21. return [clean(i) for i in str(a_list).split(',')]
  22.  
  23.  
  24. # Generates markdown for the section describing Collection Variables
  25. def gen_variables_section(list_of_variables):
  26. op = "h2.Variables Used in this Collection" + "\n"
  27. op += "||Name||Description||Example||" + "\n"
  28. for variable in sorted(list_of_variables, key=itemgetter('key')):
  29. op += "|" + variable["key"] + "| |" + variable["value"] + "|" + "\n"
  30. return op
  31.  
  32.  
  33. # Generates markdown for request section
  34. def gen_request_section(item):
  35. item = json.loads(json.dumps(item))
  36. # Heading, e.g. GET Users
  37. request_section = "h2." + "{color:#3ebb3e}" + item["request"]["method"] + "{color} " + item["name"] + "\n"
  38.  
  39. # Description
  40. if "description" in item["request"]:
  41. request_section += item["request"]["description"] + "\n"
  42.  
  43. request_section += "\nh3. Request" + "\n"
  44. # URL format
  45. request_section += "h4. Request URL" + "\n"
  46. request_section += "{panel}"
  47. request_section += "* *{color:red}Production Instance{color}:* " + item["request"]["url"]["raw"].replace("{{", "$").replace("}}", "") + "\n"
  48. request_section += "* *Staging Instance:* " + item["request"]["url"]["raw"].replace("nmvip", "nmvip-staging").replace("{{", "$").replace("}}", "") + "\n"
  49. request_section += "{panel}" + "\n"
  50.  
  51. # Headers
  52. # print("# Headers: " + len(item["request"]["header"]))
  53. request_section += "h4. Request Headers" + "\n"
  54. request_section += "||Key||Value||Description||" + "\n"
  55. for header in item["request"]["header"]:
  56. request_section += "|" + header["key"] + "|" + header["value"]
  57. description = " "
  58. if "description" in header:
  59. description = header["description"]
  60. request_section += "|" + description + "|" + "\n"
  61.  
  62. # Request Parameters
  63. add_param_section = False
  64. param_section = "\nh4. Request Parameters" + "\n"
  65. param_section += "||Parameter Type||Key||Value||Description||" + "\n"
  66.  
  67. url = item["request"]["url"]
  68. # Path Parameters
  69. if "path" in url:
  70. path_parameters = url["path"]
  71. for param in path_parameters:
  72. ps = param.decode()
  73. if "{{" in param:
  74. add_param_section = True
  75. param_section += "|" + "Path Parameter" + "|" + param.replace("{{", "$").replace("}}", "") \
  76. + "|" + " " + "|" + " " + "|" + "\n"
  77. # Query String Parameters
  78. if "query" in url:
  79. qs_parameters = url["query"]
  80. for param in qs_parameters:
  81. add_param_section = True
  82. param_section += "|" + "Query String Parameter" + "|" + param["key"] \
  83. + "|" + param["value"] + "|" + " " + "|" + "\n"
  84.  
  85. print(param_section)
  86.  
  87. if add_param_section:
  88. print("ADD PARAMETERS SECTION")
  89. request_section += param_section
  90.  
  91. # Request payload as code snippet
  92. if str(item["request"]["method"]) != "GET":
  93. request_section += "\nh4. Request Payload" + "\n"
  94. payload = "{code:title=" + "Payload" \
  95. + "|theme=FadeToGrey|linenumbers=true|language=javascript|firstline=0001|collapse=true}"
  96. # print(item["request"]["body"])
  97. if item["request"]["body"] is None:
  98. # print("No Payload")
  99. payload += "{}"
  100. else:
  101. p = json.dumps(item["request"]["body"])
  102. # print("CLEANED UP")
  103. if "raw" in item["request"]["body"]:
  104. x = clean(json.dumps(json.loads(p)["raw"]))
  105. # print(x)
  106. payload += json.dumps(json.loads(x, 'ascii'), indent=2)
  107. else:
  108. payload += "{}"
  109. payload += "{code}"
  110. # print("PAYLOAD: \n" + payload)
  111. request_section += payload
  112. payload = ""
  113. else:
  114. print("Danger!! ")
  115.  
  116. return request_section
  117.  
  118.  
  119. # Generates markdown for response section
  120. def gen_response_section(item):
  121. item = json.loads(json.dumps(item))
  122. response = json.loads(json.dumps(item["response"]))
  123. response_section = "\nh3. Response " + "\n"
  124. # print(item["name"] + " - " + str(len(response)))
  125. if len(response) > 0:
  126. code = "200*"
  127. if "code" in response[0]:
  128. code = str(response[0]["code"])
  129. else:
  130. print(response[0])
  131.  
  132. status = "OK*"
  133. if "status" in response[0]:
  134. status = str(response[0]["status"])
  135. else:
  136. print(response[0])
  137.  
  138. # Response body as code snippet, response code + status as snippet title
  139. response_section += "{code:title=" + code + " " + status \
  140. + "|theme=FadeToGrey|linenumbers=true|language=javascript|firstline=0001|collapse=true}"
  141. body = " "
  142. if "body" in response[0]:
  143. body = response[0]["body"]
  144. if response[0]["body"] is None:
  145. body = "{}"
  146. # print("BODY: \n" + body)
  147. body = json.dumps(json.loads(body, 'ascii'), indent=2)
  148. else:
  149. print("Danger!! ")
  150.  
  151. response_section += body
  152. response_section += "{code}"
  153.  
  154. return response_section
  155.  
  156.  
  157. # Generates a section for the given resource
  158. def gen_resource_section(name, group):
  159. global serial_num
  160. global working_dir
  161. resource_section = "\n"
  162. for item in group:
  163. print("\t Processing " + str(item["request"]["method"]))
  164. resource_section += gen_request_section(item)
  165. resource_section += gen_response_section(item)
  166. # Write to a separate output file
  167. file_name = str(serial_num) + "." + name + "-" + str(item["request"]["method"]) + ".txt"
  168. with open(working_dir + "\\generated\\" + file_name, 'w') as output_file:
  169. output_file.write(resource_section)
  170. serial_num = serial_num + 1
  171. # Reset this!
  172. resource_section = "\n"
  173.  
  174.  
  175. # Read in the input as JSON
  176. with open(input_file) as json_data:
  177. input_data = json.load(json_data)
  178. # Extract all variables and print them out as a table
  179. v = gen_variables_section(input_data["variable"])
  180. # print(v)
  181. # Now extract all requests ("items" in the collection) sorted by resource name ("name" in the collection)...
  182. items = sorted(input_data["item"], key=lambda x: (x['name'], x['request']['method']))
  183. # print("Number of items: " + str(len(items)))
  184. # ... and generate documentation for supported methods by resource, in alphabetical order (GET, PATCH, POST, etc.)
  185. for name, group in groupby(items, key=lambda y: (y['name'])):
  186. print("Exporting: " + name)
  187. gen_resource_section(name, group)
Add Comment
Please, Sign In to add comment