RestClient gem can be used for calling REST based web-service calls. These days I am working on integrating JasperReports with Ruby on Rails.
Jasper Reports exposes Rest apis for doing various jobs and I am using these web service methods for generating various reports etc in Ruby on Rails. This post is not about the integration of Rails with Jasper Reports ( I will be doing it very soon), but rather on how on how to use RestClient for making the web-service request.
For explaining this post, I am going to assume that our webservice server is accessible at the following location:
url = "http://localhost:8080/example_server/"
With RestClient, one can make all HTTP verb calls (POST, GET, PUT and DELETE)
Below are small examples of how to make different using RestClient. Lets assume that we need to pass some parameter while making the call and for this purpose, I will be creating a JSON data variable which will store some parameters for this example.
1st Example is for POST request
json_data = '{"param1":100, param2 = "some_value"}" result = RestClient.post url, json_data, {:content_type => :json, :accept => :json}
where json_data variable has all parameters and along with the POST request we are passing the content type parameters for the request also.
json_data = '{"param1":100, param2 = "some_value"}" result = RestClient.get url, {:content_type => :json, :accept => :json}
json_data = '{"param1":100, param2 = "some_value"}" result = RestClient.put url, json_data, {:content_type => :json, :accept => :json}
Please note that for DELETE request, I have made a little change in the url
url = "http://localhost:8080/example_server/resource" result = RestClient.delete url
In some cases webservice call requires authentication and only a user who has proper permission will be able to get the data. In these cases, after authentication, you will get a valid cookie and lets assume that this is stored in 'response' variable. So now while making the POST request, we will have to pass this cookie value also. This can be done the following way:
result = RestClient.post url, json_data, {:cookies => {"session_id" => response}, :content_type => :json, :accept => :json}
Hope this little post helps someone.