rubypostsketchup

Sending json post request in thirdparty api from sketchup


I am trying to send a post request from sketchup to the api i made.I have web dialog.On the web dialog,On click the “save” button the post request will be executed.I want to send the information as json.I have been able to access the api i made.How can i access the length,width and send the length,width,volume from the sketchup model as json.here is the model i wrote::

  def self.show_dialog
    @dialog ||= self.create_dialog
    @dialog.add_action_callback("ready") { |action_context|
      self.update_dialog
      nil
    }
    @dialog.add_action_callback("accept") { |action_context, value|
      self.update_material(value)
      @dialog.close
      nil
    }
    @dialog.add_action_callback("cancel") { |action_context, value|
      @dialog.close
      nil
    }
    @dialog.add_action_callback("save") { |action_context, value|
      self.update_material(value)
      request = Sketchup::Http::Request.new("http://127.0.0.1:5000/api/v1/projectStatus/save", Sketchup::Http::POST )
      request.start do |request, response|
        puts "body: #{response.body}"
      end
      nil
    }
    @dialog.show
  end

I want send the the post request something like this:

{
    "length": "11",
     "width": "12",
    "volume": "168"
}

Solution

  • you have 2 methods:

    JAVASCRIPT INSIDE THE PAGE

    -> send a request in javascript directly inside your webdialog as in a normal html page. For exemple, if you use Jquery:

    <html>
    <head>
       <script src="jquery-3.5.1.min.js"></script>
    </head>
    .....
    <body>
    <button id="save">save</button>
    </body>
    
    <script>
    $( "#save" ).click(function() {
      $.ajax({
        type: "POST",
        url: "http://127.0.0.1:5000/api/v1/projectStatus/save",
        data: {
          "length": "11",
           "width": "12",
          "volume": "168"
      },
        success: success,
        dataType: dataType
      });
    });
    
    </script>
    </html>
    

    IN RUBY inside your ruby by removing Sketchup ruby code, by removing Sketchup and add

      Sketchup::require 'net/http'
      ....
      @dialog.add_action_callback("save") { |action_context, value|
          self.update_material(value)
          uri = URI("http://127.0.0.1:5000/api/v1/projectStatus/sav")
          result_json = Net::HTTP.post(uri,{
            "length": "11",
            "width": "12",
            "volume": "168"
       })
        result = JSON.parse(result_json)
    
      }
    

    Hope it's help