Posting JSON data to sinatra with JQuery

I guess this post is mainly useful when you want to build Restful API with Sinatra.   Let’s say you want to pass JSON data to Sinatra backend using JQuery. so you may got very first question is How to parse JSON POST Data in Sinatra rest api ?  am i right ?

so here is full example which demonstrate how to send JSON data to Sinatra REST API.

JQuery Code:

$.ajax({
url: '/test_api',
type: 'POST',
dataType: 'json',
contentType: "application/json",
data:JSON.stringify(data),
success: function(data){
}
})

let’s say data (json variable) contain complex data like

{
"topo": [
    {
      "dpid": "00:00:00:00:00:00:00:03",
      "ports": [
                 3,
                 2
                ]
    }
   ],
"app": "vm_migration"
}

Ruby Sinatra Rest Function

post '/test_api', :provides => :json do
  begin
     # bellow line get post json data
     params = JSON.parse(request.env["rack.input"].read) 
     # you can access key value like bellow
     app = params["app"]
     params["topo"].each do |topo|
            dpid = topo["dpid"]
            # getting each value of key using each
            topo["ports"].each do |port| 
                #Process Data
            end            
        end
  rescue Exception => e
    return e.message
  end
end

Hope it is useful..  plz do comment if it is useful for you..
🙂

any question related to post, feel free to ask.

Advertisements

One thought on “Posting JSON data to sinatra with JQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s