One of Onshape's core principles is extensibility. Built into Onshape are numerous ways for the product to be modified, added onto, and customized to fit the unique needs of users. Right panel apps are one of he most versitile and convenient ways to add your own custom experience to Onshape. This guide is intended to get you started with building your first right panel app.
-
This guide is intended to be as introductory as possible, with the goal of making your first very simple app. For a much more comprehensive app development guide, visit the official Onshape Development site.
-
As we saw with API usage, talking to Onshape's servers requires authentication. The same is true with right panel apps. You may not simply add any content or any program onto Onshape. For good reason, there are specific security measures that must occur, even for the simplest app. The following tutorial is as simple as it gets, but there are still several not-so-simple components required. With that warning, let's begin.
If you want to create a right panel app, technically you will be creating an "OAuth application." OAuth, short for Open Authentication, is how Onshape authenticates users and applications. The OAuth protocol enables an application (like your right panel app) to access a resource that is under the control of someone else (like the Onshape API).
At the risk of getting into the weeds, it is important to understand the OAuth authorization flow, because your app will have to follow it.
With OAuth, you register your app with Onshape (we'll do that in the next step) and are given a set of keys. These keys get exchanged for an Access Token that grants you access to certain resources, like the API. Every now and then that token expires and in order to continue to access the resources, you are required to get a new token. For this, you are provided with a refresh token. Sending the refresh token to Onshape's authentication server will provide you with your updated access token and a new refresh token.
Figure 1 - Oauth Authorization Flow
The first step to the OAuth flow is when a user opens your right panel app. That initiates a request for Onshape to authorize access for your app.
Once the app has been authorized, the user will be redirected to a predefined URL together with a code that will be used to request an access token from Onshape. Therefore, the redirect URL needs to contain a script that can capture the authorization code. We will write a flask app for this.
The access token is the token you will use to authenticate requests to the Onshape API.
Refreshing the access token will also provide you with an updated refresh token that will be used in the next refresh access token request. Your app needs to store both the access token and the refresh token and update them with each refresh of the token.
The authorization token must accompany any call to the API, this is done by adding the token to an "Authorization" field in the header of each request:
'Authorization' : 'Bearer [authorization code here]'
If correctly authenticated, the response from the REST API call will be a stream of JSON data with an HTTP response code of 200.
Even the simplest right panel app requires the above steps. In summary, for our app to function, our next steps are:
- Create an OAuth App through the Onshape Developer Portal
- Create a local flask app to handle the OAuth requests
Let's get started.
First, log into the Onshape Developer Portal, https://dev-portal.onshape.com/, and click on "OAuth applications" on the left side of the screen. Then click the "Create new OAuth application" button in the top right. You will be taken to the Create an OAuth application page. To create your first app, you'll need to fill out a few fields. Below, we explain exactly what you need to enter.
- Name – this is the application name that you wish to display to the users. If your app will eventually end up in the App store, you would want to make it unique and descriptive. But for now, let's just go with something like:
My First Right Panel App
- Primary format - this string uniquely identifies your application and is a marker for the data it might store on Onshape servers. It should take the form of a Java style reverse domain name. This value cannot be changed after the application is registered. Something like:
com.matt.first-app
- Summary – this is a description of your application. This is displayed to the user when they’re asked to grant the application permission to access their data.
This is my first right panel app. It makes some basic API calls.
- Redirect URLs - Your application must specify at least one URL used in the OAuth protocol exchanges. This URL must also use SSL (a URL that begins with https) or be in the form
http://localhost:<port>. We will use the "localhost" option (our flask app), since we don't have an actual web server to be part of the OAuth process. Type in the URL below (which we will create in the next step).
http://localhost:8000/oauthRedirect
- Admin Team – this is an optional field. If defined, members of the admin team selected will have access to make changes to this OAuth application.
No Team
- OAuth URL – This URL is the "Authentication Page" for your application. This is the first URL called from the Onshape Applications page. The page hosted at this URL should handle the OAuth authentication. Once your application’s server has been authenticated on behalf of the user, that user should be redirected to your applications content. We are developing locally, so we can leave this blank.
blank
- Permissions – this is also called application scope and it defines what access rights you want your application to have with regards to the user’s data. Check off the first three permissions:
Application can read your profile information
Application can read your documents
Application can write to your documents
Once you have the fields filled out, click the Create application button.
Important: As soon as you create your app, you will be provided with a secret key. Let's save that now. Create a new file called oauth_key.json. In that file, type the following:
{
"OAUTH_CLIENT_ID": "client id",
"OAUTH_CLIENT_SECRET": "the key you were just given"
}
Replace the OAUTH_CLIENT_SECRET with the key you were just given and then close the dialog box in the developer portal.
Congrats, your app has now been created! In the "Details" tab, you will see your OAuth client identifier. Replace OAUTH_CLIENT_ID in your oauth_key.json file with that key.
In the developer portal, you will notice a warning letting you know "this application has no extensions." Let's do that now.
Click the "Extensions" tab then the "Add extension" button. Complete these form fields:
- Name - This will be the name of the actual right panel app extension. An OAuth application can actually have several extensions. Something like:
Local Testing
- Description - This can be anything
A simple right panel app
- Location - How users will interact with the app
Element right panel
- Context - This basically defines what parameters will be sent from Onshape to our app.
Inside document
- Action URL - The URL of the page that you wish to load in the right element panel. Parameters can be added as arguments. For this, we will be creating a local flask app (next section of this tutorial).
http://localhost:8000/login
- Icon - Any good right panel app needs a good icon. Any SVG under 1 MB will do. If you need one, feel free to use this one:
Finally, we are ready to add our app to the Onshape App Store. Don't worry, it will only be visible to you (and anyone you add to your admin team).
Click the Details tab and then click the "Create store entry" button.
Let's fill in the required fields.
-
Description
My first app -
Vendor
Me, Inc. -
Category
Utilities
Click the Create button and your app should show up in under Store entries.
Go to the Onshape App Store and your app should be there in the Utilities section. Or find it by using search. Once you find it, click it and click the Subscribe button then "Get for free."
Go back to Onshape and open a part studio and your new app should be there waiting for you! Nice work. Click the app to open it and you should get some sort of error like localhost refused to connect.. We haven't actually built the app yet. That's the next section. Let's go.
Note: for this section, we are going to assume you are developing on a Mac or Linux machine (the commands are similar). For Windows users, some commainds may differ. In particular, on Windows:
- do not set the
FLASK_APPenvironment variable - Use
flask --app app run -p 8000to launch the app - Python will probably not be installed by default. Install here: https://www.python.org/downloads/
- The command to create a virtual environment is the same, but to activate it,
.\.venv\Scripts\activate
Somewhere on your computer, make a new folder called my-first-flask-app.
Inside that folder, we need:
- That
oauth_key.jsonfile you made earlier to store your OAuth keys - A file called
app.py - A folder called
templateswith a file inside it calledindex.html
So, the file structure should look like this:
my-first-flask-app/
├── oauth_key.json
├── app.py
├── templates/
│ ├── index.html
The code for index.html is straightforward HTML.
<html>
<head>
<title>Hello world!</title>
</head>
<body>
It works!!
</body>
</html>The code for app.py is also straightforward (for now).
This is the most basic flask app code. This will direct any requests to the root directory ('/') to a function that renders our index.html page.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')In a terminal window, navigate to your my-first-flask-app directory.
Start a virtual environment.
python3 -m venv .venv
source .venv/bin/activateYour terminal prompt should now start with (.venv)
Install flask
pip install flask
Set an environment variable to make flask easier to run.
export FLASK_APP=app.py flask run
Launch your flask app.
flask run -p 8000
You now have a local web server listening to requests on port 8000. If we visit localhost:8000 our app.py code will respond by rendering index.html. Let's try it! Open your web browser and type localhost:8000 into the address bar.
You should see your "It works!" message. Wohoo.
Remember, the whole reason we were making a flask app was to handle all of the OAuth requests in Onshape. Go back to your Onshape document, close and open your new right panel app.
You should get a new error. Before, your app was calling localhost:8000 and there was nothing there. Now, we are getting a "Not found" error because we need to construct the login and authentication process.
In your terminal window, press Ctrl+C to kill the flask app for now.
While your in terminal (but still in your virtual environment), install the requests library:
pip install requests
After installing requests, deactivate and reactivate your virtual environment.
deactivate
source .venv/bin/activateAt the top of your code, modify your from flask import... line and then add four more below it:
from flask import Flask, render_template, request, redirect, url_for
import json
import requests
from datetime import datetime, timedelta
import osThose are all of the libraries and modules you will need for your app.
Leave the next line alone. You should have:
app = Flask(__name__)Below that, let's set some global variables.
OS_DOMAIN, OS_USER_ID, USER_NAME = None, None, None
ACCESS_TOKEN, REFRESH_TOKEN, EXPIRES_AT = None, None, NoneNext, we are going to import our OAuth keys from the oauth_key.json file we created.
with open('oauth_key.json') as f:
oauth_keys = json.load(f)
OAUTH_CLIENT_ID = oauth_keys['OAUTH_CLIENT_ID']
OAUTH_CLIENT_SECRET = oauth_keys['OAUTH_CLIENT_SECRET']Finally, we are going to do all of our "routing." In other words, we need to define how our app responds based on whether someone is requesting localhost:8000/ or loalhost:8000/oauthRedirect or localhost:8000/login.
We already have the code for @app.route('/'). The code for @app.route('/login/') is below
@app.route("/login/")
def login():
# When the app extension is first opened, this app page is called.
# It collects user information and redirects the user to Onshape's OAuth authorization page.
global ACCESS_TOKEN, REFRESH_TOKEN, EXPIRES_AT
global OS_DOMAIN, OS_USER_ID
# set the domain, user ID for use later
OS_DOMAIN = request.args.get('server')
OS_USER_ID = request.args.get('userId')
# If we don't have an access token, go get one.
if not ACCESS_TOKEN:
return redirect(
"https://oauth.onshape.com/oauth/authorize?response_type=code&client_id={}".format(
OAUTH_CLIENT_ID.replace("=", "%3D")
)
)
# If our access token has expired, go get a new one.
elif datetime.now() >= EXPIRES_AT - timedelta(minutes=20):
response = requests.post(
"https://oauth.onshape.com/oauth/token?grant_type=refresh_token&refresh_token={}&client_id={}&client_secret={}".format(
REFRESH_TOKEN.replace('=', '%3D'),
OAUTH_CLIENT_ID.replace('=', '%3D'),
OAUTH_CLIENT_SECRET.replace('=', '%3D')
),
headers={'Content-Type': "application/x-www-form-urlencoded"}
)
response = response.json()
print(response)
ACCESS_TOKEN = response['access_token']
REFRESH_TOKEN = response['refresh_token']
EXPIRES_AT = datetime.now() + timedelta(seconds=response['expires_in'])
return redirect(url_for("index")) Finally, add the code for @app.rounte('/oauthRedirect/').
@app.route("/oauthRedirect/")
def authorize():
# When the user authorizes the OAuth integration, Onshape's OAuth
# authorization page will redirect the user to this page, as registered as the redirect URL.
auth_code = request.args.get('code')
if not auth_code:
return "<p>User authentication failed!</p><p>Error: " + str(request.args.get('error')) + "</p>"
# Use authorization code to get tokens
response = requests.post(
"https://oauth.onshape.com/oauth/token?grant_type=authorization_code&code={}&client_id={}&client_secret={}".format(
auth_code.replace('=', '%3D'),
OAUTH_CLIENT_ID.replace('=', '%3D'),
OAUTH_CLIENT_SECRET.replace('=', '%3D')
),
headers={'Content-Type': "application/x-www-form-urlencoded"}
)
response = response.json()
global ACCESS_TOKEN, REFRESH_TOKEN, EXPIRES_AT
ACCESS_TOKEN = response['access_token']
REFRESH_TOKEN = response['refresh_token']
EXPIRES_AT = datetime.now() + timedelta(seconds=response['expires_in'])
return redirect(url_for("index"))Make sure you are in your virtual environment and re-launch your app:
flask run -p 8000
Go back to Onshape, close and open your app and it should work! You might be asked to authorize the app for the first time, but then you should see your "It works!" message.
The last step is to make an API call from within flask.
To do so, we need to pass some parameters from Onshape to our app through the Action URL.
Go back to the Developer portal. Under OAuth Extensions, find your app, click the Extensions tab, then click the "Edit" button. The Action URL should be
http://localhost:8000/login
Change it to
http://localhost:8000/login?did={$documentId}&wvm={$workspaceOrVersion}&wvmid={$workspaceOrVersionId}&eid={$elementId}
That will send the DID, workspace or version ID, and EID to our app.
Next, add three global variables to the top of app.py to handle these new parameters.
DID, WID, EID = None, None, None
In our def login(): function, we are already getting a couple of request arguments:
OS_DOMAIN = request.args.get('server')
OS_USER_ID = request.args.get('userId')Add to that three more:
DID = request.args.get('did')
WID = request.args.get('wvmid')
EID = request.args.get('eid')Finally, add an API request to your def index(): function. This should look familiar. We are simply passing the DID, WID, and EID to the GET /api/parts/ endpoint. Our ACCESS_TOKEN provides authorization. We parse through the JSON response to build a PARTS[] array and send it to our index.html template.
response = requests.get(
os.path.join(
OS_DOMAIN,
"api/parts/d/{}/w/{}/e/{}/".format(
DID, WID, EID
)
),
headers={
"Content-Type": "application/json",
"Accept": "application/json;charset=UTF-8;qs=0.09",
"Authorization": "Bearer " + ACCESS_TOKEN
}
)
PARTS = []
if response.ok:
response = response.json()
for i in range(len(response)):
PARTS.append(response[i]["name"])To send the PARTS[] array from app.py to the index.html template, change the last line of the function to be:
return render_template('index.html', parts=PARTS)Loop through the received parts array by adding this code to your index.html page, right after "It works!"
All of the parts in this part studio:
{% for part in parts %}
<p>{{ part }}</p>
{% endfor %}In order to see your changes in the app:
- save your changes to
index.htmland any other files you changed - kill the flask app py pressing Ctrl+C in terminal
- relauch the app with
flask run -p 8000 - close and reopen the right panel app
Congrats, you now have an app that you can run on any Onshape document! Try going back to our Hello World document,
and opening your new right panel app. You should see a long list of parts!
Right now, the app only lists the part names. The challenge: list both part names and part IDs. Hint: you don't need to mess with the API call; the part IDs are already in the JSON. Just add the "partId" property to the list that gets sent to index.html. Maybe even try making a multidimensional array.
Update your file structure to look like this:
my-first-flask-app/
├── oauth_key.json
├── app.py
├── templates/
│ ├── index.html
├── static/
│ ├── index.css
Then add this line inside the <head> section of your index.html file:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='index.css') }}" />
Finally, edit index.css to give your page some style. Get creative.
Note: The completed files for this exercise are in this GitHub repsository.
