-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmaster_writer.py
126 lines (106 loc) · 5.04 KB
/
master_writer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import json
import os
import nbformat as nbf
from onshape_client.client import Client
from API_generator import generate_api
# Setup Onshape Client with API keys
base = 'https://cad.onshape.com'
access = ""
secret = ""
for _, _, files in os.walk('.'):
if "OnshapeAPIKey.py" in files: # Put API key in project folder
exec(open("OnshapeAPIKey.py").read())
break
client = Client(configuration={'base_url': base,
'access_key': access,
'secret_key': secret})
# Get all info from Onshape Open API
# Source (Glassworks): https://cad.onshape.com/glassworks/explorer/
response = client.api_client.request(method='GET',
url=base + '/api/openapi',
query_params={},
headers={},
body={})
openApi = json.loads(response.data)
###################### Start writing the Jupyter notebook #########################
nb = nbf.v4.new_notebook() # the notebook
cells = [] # the cells in the notebook (ordered -> use append())
"""
To add text: nbf.v4.new_markdown_cell(text)
To add code: nbf.v4.new_code_cell(code)
Then, append to cells
"""
# General info as an introduction
cells.append(nbf.v4.new_markdown_cell('''# Onshape REST API
Below is the Python version of all the Onshape REST API endpoints in the form of code snippets. You can follow guidance in [this GitHub repository](https://github.com/PTC-Education/Python-OpenAPI) to import these snippets in your own Jupyter notebook using Google Colab. Meanwhile, the official full documentation of all API endpoints can be found on [this website](https://cad.onshape.com/glassworks/explorer/).
Note: this Jupyter notebook is designed to be launched and used in Google Colab for the best experience.
'''))
cells.append(nbf.v4.new_markdown_cell('''# 0. Setup
**Important:** you have to run ALL cells in this section before you can properly use the rest of the code snippets. When importing snippets to your own Jupyter notebook, you have to import ALL cells in this section and run them before executing any of the snippets in this notebook.
'''))
cells.append(nbf.v4.new_code_cell('''#@title Import and Setup Onshape Client
!pip install onshape-client
from onshape_client.client import Client
from onshape_client.onshape_url import OnshapeElement
import json
#@markdown Chage the base if using an enterprise (i.e. "https://ptc.onshape.com")
base = 'https://cad.onshape.com' #@param {type:"string"}
#@markdown Would you like to import your API keys from a file, or copy and paste them directly?
keyImportOption = "Upload Keys from File" #@param ["Upload Keys from File", "Copy/Paste Keys"]
from IPython.display import clear_output
clear_output()
print("Onshape Client successfully imported!")
if keyImportOption == "Upload Keys from File":
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
execfile(fn)
client = Client(configuration={"base_url": base,
"access_key": access,
"secret_key": secret})
clear_output()
print('Onshape client configured - ready to go!')
else:
access = input("Paste your Onshape Access Key: ")
secret = input("Paste your Onshape Secret Key: ")
client = Client(configuration={"base_url": base,
"access_key": access,
"secret_key": secret})
clear_output()
print('Onshape client configured - ready to go!')
'''))
# A list of all API endpoint paths
endpoints = list(openApi['paths'].keys()) # each item is a str
# A list of all API categories
temp_tags = openApi['tags'] # each item is a dict {'name': str, 'description': str}
tags = {} # dict{name: description}
# Note that temp_tags is in alphebatical order (not the same for endpoints)
for item in temp_tags:
tags[item['name']] = item['description']
curr_tag = "None"
tag_ind = 0
for endpoint in endpoints:
# All types of the endpoint (get, post, delete)
api_type = list(openApi['paths'][endpoint].keys())
# Check if need to start a new section
if openApi['paths'][endpoint][api_type[0]]['tags'][0] != curr_tag:
tag_ind += 1
curr_tag = openApi['paths'][endpoint][api_type[0]]['tags'][0]
if curr_tag in tags:
tag_descript = tags[curr_tag]
else:
tag_descript = None
cells.append(nbf.v4.new_markdown_cell('''# {}. {}
{}
'''.format(tag_ind, curr_tag, tag_descript)))
# Generate and add code for each type of the endpoint
for typ in api_type:
try:
cells.append(nbf.v4.new_code_cell('''{}'''.format(generate_api(openApi, endpoint, typ))))
except:
print("Error encountered for endpoint:", endpoint, typ)
# Write all the cells in a Jupyter notebook
nb["cells"] = cells # add cells to notebook
with open("API_Snippets.ipynb", 'w') as f:
nbf.write(nb, f) # write the notebook
print("Notebook created successfully!")