REST Client – simple DSL for accessing HTTP and REST resources
A simple HTTP and REST client for Ruby, inspired by the Sinatra’s microframework style of specifying actions: get, put, post, delete.
I found this Ruby-Gem very useful while building App. so i will describe here how to use REST Client in Ruby
Simple example for REST Client POST Request.
res=RestClient.post 'http://localhost:8080/wm/test/json', params.to_json, :content_type => :json, :accept => :json
result = JSON.parse(res)
above example send post request to my local server, which takes few parameters in form of json and
return output in form of JSON.
likewise, you can use any method GET,PUT,DELETE.
Hope you’ll like dis 🙂
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.
let’s say data (json variable) contain complex data like
Ruby Sinatra Rest Function
post '/test_api', :provides => :json do
# 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|
rescue Exception => e
Hope it is useful.. plz do comment if it is useful for you..
any question related to post, feel free to ask.
This post shows you how you can connect to MySQL in Ruby. I’m assuming that you already aware with basic SQL Operation like how to create database, table and insert, delete, update statement. So I’m directly dive in coding part, as I believe that more theory can confuse us. so I gonna explain you straight to the point.
okay so first we try to connect to the MySQL server and fetch all rows from table “test”.
con = Mysql.new('localhost', 'root', 'root', 'test')
rs = con.query('select * from demo')
rs.each_hash do |row|
puts row['uid'] + " " + row['name']
to run this basic example you need to use following command
for insert statement you can use following code.
con.query("INSERT INTO demo values('"+id+"','"+name+"','"+mno+"')")
now you can able to perform basic insert,update and delete statement in same way.
Enjoy d code.. 🙂