Welcome to the Onshape forum! Ask questions and join in the discussions about everything Onshape.

First time visiting? Here are some places to start:
  1. Looking for a certain topic? Check out the categories filter or use Search (upper right).
  2. Need support? Ask a question to our Community Support category.
  3. Please submit support tickets for bugs but you can request improvements in the Product Feedback category.
  4. Be respectful, on topic and if you see a problem, Flag it.

If you would like to contact our Community Manager personally, feel free to send a private message or an email.

Best way to use onshape via python

arpit_agarwal087arpit_agarwal087 Member Posts: 9 EDU
I am wondering what is the best way to work with onshape using python. I saw that the onshape-client is archived. Is there any other alternative? Any suggestions would be helpful

Comments

  • billy2billy2 Member, OS Professional, Mentor, Developers, User Group Leader Posts: 2,071 PRO
    edited March 2023
    If you want to program a partstudio then you'll be using featurescript. If you want to access an assembly, you'll be using the API which works with any language. Bottom line, if you want to program inside OS, use featurescript.

    I looked though onshape-client which is a thorough python app that exercises many of the API's options.

    The example index.html is larger than my entire website including client code, server code & all modules used to talk to OS. It's a large example.

    Read the API and pick what you want todo, then do it. It doesn't require a mountain of code.

    There's different ways to access the OS api:
    -login into OS and use localhost to call the API. Logging into OS gives your computer rights to use the API. (I don't use this)
    -register with OS API and get api keys, now you have 2 ways to get to the API
    --you can easily get to your account and access your data
    --you can register with the app store and request access to other users data. This requires oauth2.

    The way I do it:
    -I open a socket between the client & server
    -My server makes connections to OS server using api keys to my data.
    -I have registered in the app store and have had access to other OS data, but I don't do that any longer.

    So, ideally here's the preferred path:
    client-->socket-->server-->post-->API-->server-->client

    So I can ask OS for images of all documents and the API will start sending images asynchronously back to the client. The client then unpacks json for the images and I update the page.

    This could take some time, creates a ton of internet traffic and it's fun. You could start responding to the rendered page by deleting stuff which would in turn overlay more internet traffic through the socket and you could delete based on the images OS sent to you. It's your responsibility to up date your local page and remove the images of the documents you've deleted.

    If you want to use python with OS, then you'll be using the API. If you want to program inside OS use featurescript, it's much better than python for programming inside OS.



  • arpit_agarwal087arpit_agarwal087 Member Posts: 9 EDU
    Thanks for your response. I am looking to talk to OS with python. However, I am looking for a beginner example on how to do it. You solutions look very good. Is it available for public use or could you share some snippets for somebody starting to use the API. 
  • eric_pestyeric_pesty Member Posts: 1,951 PRO
    Have you looked at this?
    https://www.youtube.com/watch?v=A1AOfzhy5XE
    There are some links in the description to some colab notebooks.

    I was able to get some basic stuff through the API thanks to these examples (with no prior knowledge of how any of it worked...)


  • billy2billy2 Member, OS Professional, Mentor, Developers, User Group Leader Posts: 2,071 PRO
    edited March 2023
    Go look at the link above supplied by @eric_pesty. Alnis gets things running with minimal effort.

    My code, won't help you. I run node and I'm running off a server, the login is totally different.

    Just keep in mind, that when you login into onshape, your computer has access to onshape's api. For me, my server never logs into onshape so I use a different method to access onshape.

    https://cad.onshape.com/glassworks/explorer/

    Here's a listing of the current API calls. 

    Not all calls are listed though, in many cases, you inspect the network traffic for onshape and capture the call that the onshape client makes to the servers. Let's say you want gltf data. It's not documented. So you open the debug console in your browser, then click on the gltf command inside onshape and capture the call the onshape client is making to the onshape server. 

    The API documentation is not complete by any means, but you can get by.

    Any cloud application, you can hijack the commands they're using.

    As an easy goal, try and retrieve a listing of your documents. Alnis is listing a public document so I'm not sure you have access to your own stuff. I've never run the API from localhost. You should have access to your documents because your client has access.

    REST is a JSON file and there should be a function call in python to convert JSON into a python object. Then you'll need to create HTML tags and display the results in a browser or just print it out to a console.

    The reason I switched to programming in node is because of JSON. Love/hate javascript, my server code is javascript and the client code is javascript. The object that's passed around is native on my server & client. I can copy code from my server and paste it into the client and make your computer parse the data. My server is a traffic cop and directs the data to clients. Then, the work begins on your computer. I only have one server instance, so I make sure it's not parsing any data. I spreading the process across all those who come to my site. Maybe I should begin a visit to site with a warning "I don't use cookies but I do use your cpu".

    When you post, you'll be sending data back to the server in a JSON format that you converted from python back to JSON. Python objects are very similar to javascript objects and may not be an issue. But..... I would run your converted the python object through a JSON linter to insure compatibility, you don't want to debug this through the onshape server.

    This forum is the best place to ask questions but most here write featurescripts. Tech support has a lot guys now that can help with basic API questions.

    Eventually you'll want a server so others can experience your API magic. Servers are cheap and will make your magic accessible to all.

  • arpit_agarwal087arpit_agarwal087 Member Posts: 9 EDU
    I have looked at the google colab. However, it depends on onshape_client which is archived. That is why I am looking for another solution. 
  • arpit_agarwal087arpit_agarwal087 Member Posts: 9 EDU
    I did a stupid mistake of replacing access_key with secret_key while making request. I am able to create a new document using the onshape-client python example. However, I am wondering how to do it without the onshape-client python as it is archived project.

    from onshape_client import OnshapeElement, Client
    client = Client()
    new_doc = OnshapeElement.create("Engine")
  • liam_brennan625liam_brennan625 Member Posts: 5
    Are there any updates on this since March? The onshape-clients repo is still archived and I can't seem to find what the intended alternative is. For now, I guess just using the REST api with the python requests library works ok?
  • guillauem_dguillauem_d Member Posts: 17
    billy2 said:
    Go look at the link above supplied by @eric_pesty. Alnis gets things running with minimal effort.

    My code, won't help you. I run node and I'm running off a server, the login is totally different.

    Just keep in mind, that when you login into onshape, your computer has access to onshape's api. For me, my server never logs into onshape so I use a different method to access onshape.

    https://cad.onshape.com/glassworks/explorer/

    Here's a listing of the current API calls. 

    Not all calls are listed though, in many cases, you inspect the network traffic for onshape and capture the call that the onshape client makes to the servers. Let's say you want gltf data. It's not documented. So you open the debug console in your browser, then click on the gltf command inside onshape and capture the call the onshape client is making to the onshape server. 

    The API documentation is not complete by any means, but you can get by.

    Any cloud application, you can hijack the commands they're using.

    As an easy goal, try and retrieve a listing of your documents. Alnis is listing a public document so I'm not sure you have access to your own stuff. I've never run the API from localhost. You should have access to your documents because your client has access.

    REST is a JSON file and there should be a function call in python to convert JSON into a python object. Then you'll need to create HTML tags and display the results in a browser or just print it out to a console.

    The reason I switched to programming in node is because of JSON. Love/hate javascript, my server code is javascript and the client code is javascript. The object that's passed around is native on my server & client. I can copy code from my server and paste it into the client and make your computer parse the data. My server is a traffic cop and directs the data to clients. Then, the work begins on your computer. I only have one server instance, so I make sure it's not parsing any data. I spreading the process across all those who come to my site. Maybe I should begin a visit to site with a warning "I don't use cookies but I do use your cpu".

    When you post, you'll be sending data back to the server in a JSON format that you converted from python back to JSON. Python objects are very similar to javascript objects and may not be an issue. But..... I would run your converted the python object through a JSON linter to insure compatibility, you don't want to debug this through the onshape server.

    This forum is the best place to ask questions but most here write featurescripts. Tech support has a lot guys now that can help with basic API questions.

    Eventually you'll want a server so others can experience your API magic. Servers are cheap and will make your magic accessible to all.

    Hello there,

    I'm having a very hard time creating simple sketches and extrusions that are not already documented in the API documentation (https://onshape-public.github.io/docs/api-adv/featureaccess/#create-a-sketch). For example, I can't seem to create a simple square sketch (the documentation explains it for circles, but not for squares). So I tried the following method:

    • Create a square sketch by hand
    • Get the existing feature list of the part to see what the feature JSON looks like for the square sketch
    • Create a new feature with the same JSON format

    But it never works! :( I always get one error or another, it seems like the feature definition is not exactly in the same format that is output by the get feature list API.

    So I tried the network traffic method you mentioned using the Chrome DevTools, but I can't find any API calls. I looked at the WebSocket, but it's all binary, and I didn't manage to find any actual data I could copy and paste to execute the same command programmatically.

    Any help on that?

  • Paul_J_PremakumarPaul_J_Premakumar Member, Onshape Employees Posts: 220
    edited August 5
    @guillauem_d,

       We are working to improve our documentation. Sketch/Feature creation via the client happens via websockets and not via REST, hence you do not see it. To create a square (or any other sketch), it is best to start of with the basic shape (line in this case and work your way up). The parameter for each line ( here I am using inches ) are computed as follows

    /**
     * x : x position in inches
     * y : y position in inches
     * width : line width in inches (used to calculate end position)
     * height : line height in inches (used to calculate end position)
     **/
    INCH = 0.025400051;
    distance = Math.sqrt(width * width + height * height);
    line.startParam = 0;
    line.endParam = distance * INCH; // Normalize everything to inches
    line.pntX = x * INCH;
    line.pntY = y * INCH;
    // Direction must be a unit vector.
    line.dirX = width / distance;
    line.dirY = height / distance;

    // Here is the request body to a square of side 0.25 meters
    {
     feature": {
        "btType": "BTMSketch-151",
        "featureType": "newSketch",
        "name": "Sketch 1",
        "parameters": [
          {
            "btType": "BTMParameterQueryList-148",
            "queries": [
              {
                "btType": "BTMIndividualQuery-138",
                "deterministicIds": [
                  "JCC"
                ]
              }
            ],
            "parameterId": "sketchPlane"
          }
        ],
        "entities": [
          {
            "btType": "BTMSketchCurveSegment-155",
            "offsetCurveExtensions": [],
            "startPointId": "Line1.start",
            "endPointId": "Line1.end",
            "startParam": 0,
            "endParam": 0.25,
            "geometry": {
              "btType": "BTCurveGeometryLine-117",
              "pntX": 0,
              "pntY": 0,
              "dirX": 1,
              "dirY": 0
            },
            "entityId": "Line1"
          },
          {
            "btType": "BTMSketchCurveSegment-155",
            "offsetCurveExtensions": [],
            "startPointId": "Line2.start",
            "endPointId": "Line2.end",
            "startParam": 0,
            "endParam": 0.25,
            "geometry": {
              "btType": "BTCurveGeometryLine-117",
              "pntX": 0.25,
              "pntY": 0,
              "dirX": 0,
              "dirY": 1
            },
            "entityId": "Line2"
          },
          {
            "btType": "BTMSketchCurveSegment-155",
            "offsetCurveExtensions": [],
            "startPointId": "Line3.start",
            "endPointId": "Line3.end",
            "startParam": 0,
            "endParam": 0.25,
            "geometry": {
              "btType": "BTCurveGeometryLine-117",
              "pntX": 0.25,
              "pntY": 0.25,
              "dirX": -1.0,
              "dirY": 0
            },
            "entityId": "Line3"
          },
          {
            "btType": "BTMSketchCurveSegment-155",
            "offsetCurveExtensions": [],
            "startPointId": "Line4.start",
            "endPointId": "Line4.end",
            "startParam": 0,
            "endParam": 0.25,
            "geometry": {
              "btType": "BTCurveGeometryLine-117",
              "pntX": 0.0,
              "pntY": 0.25,
              "dirX": 0.0,
              "dirY": -1.0
            },
            "entityId": "Line4"
          }
        ]
      }
    }
  • Paul_J_PremakumarPaul_J_Premakumar Member, Onshape Employees Posts: 220
    An alternate approach would be to define your sketch using FeatureScript for example: https://cad.onshape.com/documents/873712d7c9b0f73547892997/w/1d8273691f7a21c45fedd59b/e/84848ee8a766309fa35167c5 and then create the feature using the REST API. The POST body in this case is a lot shorter and you get a much richer API to work with geometry.

    {
      "feature": {
          "btType": "BTMFeature-134",
          "namespace": "e84848ee8a766309fa35167c5::m10dca519a5dae231dd268dc3",
          "name": "Square Sketch 1",
          "parameters": [],
          "featureType": "squareSketchFeature"
        }
    }
    Hope that helps.
  • fstfst Member Posts: 59 ✭✭
    Depending on what you want to do (and which existing features you expect) it might be worth to look into FreeCAD. Pretty much everything can be done in Python there, from simple macros to full workbenches.
Sign In or Register to comment.