REST Client Example in Ruby - ruby

Can anyone explain me with an example, by using REST Client to do GET/POST/PUT operations in a Rest web service?
In POST/PUT, using REST Client, need to pass the whole xml body to do
POST/PUT operations.
For example, Using REST Client
I need to get the content of a service using,
RESTClient.get(url)
POST an xml to an url:
RESTClient.post(url,entirexml)
PUT an xml to an URL:
RESTClient.put(url,entirexml)
DELETE using REST CLIENT.
Can anyone help me with examples for all the REST Client HTTP METHODS with example?
I need to send the whole XML along with namespace to a rest service using PUT/POST operations of REST Client.
If anyone have examples on this, kindly post then please.

require 'rest-client'
RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}}
RestClient.get 'http://example.com/resource'
xml = '<xml><foo>bar</foo><bar>foo</bar></xml>'
RestClient.post 'http://example.com/resource', xml , {:content_type => :xml}
RestClient.put 'http://example.com/resource', xml , {:content_type => :xml}
RestClient.delete 'http://example.com/resource'
See more examples and documentation at https://github.com/rest-client/rest-client

The Readme file at the git site for the rest-client gem has a whole bunch of examples of how to do requests, include parameters, etc.
I'd start with that.
If there are specific things that are not working, then it generally helps to post the code you've tried that you think SHOULD be working, and then it's usually easier for people to tell where you are going wrong.

Related

how to call method in one application from another application in ruby on rails

I want to call the method and get the response in my application from another application in Ruby on Rails technology, but here cross site scripting problem is there. so, i can i resolve this issue please help me it would be great.
http://video_tok.com/courses/get_course
def get_course
#course = Course.find(params[:id])
end
now i want to call this above method from this application which is running in edupdu.com domain
http://edupdu.com/call_course_method
def call_course_method
#course = redirect_to "http://video_tak.com/courses/get_course/1"
end
but it would be redirect into video_tak.com application.
i want to call get_course method and get #course object internally without redirect to another site.
Thanks in advance.
Cross-domain AJAX is indeed a problem, but none that could not be solved. In your get_course method you could return the course objects as a JSON response like so:
render json: #course
From there on you could either retrieve the course through JavaScript (AJAX), here you should use JSONP or inside Rails by issuing a HTTP GET request.
AJAX with JSONP
There is JSONP (JSON with padding), which is a communication technique for JavaScript programs to provide a method to request data from a server in a different domain. Look at
the documentation of jQuery.getJSON() and scroll down to the JSONP section.
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead. See the
discussion of the jsonp data type in $.ajax() for more details.
HTTP GET request
Simply use the Net::HTTP class:
require 'net/http'
require 'json'
url = URI.parse('http://video_tak.com/courses/get_course/1')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) do |http|
http.request(req)
end
course_json = JSON.parse(res.body)
If you provide methods for your model to convert JSON into a domain object of yours, you can take it from there.
RPC
You can also use RPC to invoke methods between different Ruby processes, although I recommend this the least I do not want to omit it. There are several remote procedure call (RPC) libraries. The Ruby standard library provides DRb, but there are also implementations based on Ruby on Rails, for instance the rails-xmlrpc gem which allows you to implement RPC based on the XML-RPC protocol or the alternative protocol using JSON with json-rpcj
You will probably find even more libraries when searching for Rails RPC. From whatever library you pick, the concrete solution will differ.

Writing unit tests in Ruby for a REST API

I've written a basic REST API using sinatra.
Does anyone know the best way to write tests for it? I would like to do so using Ruby.
I've done my initial testing using curl. But I'd like to do something more robust. This is my first API - is there anything specific I should be testing?
The best way is a matter of opinion :) Personally, I like simple and clean. With tools like minitest, Watir and rest-client, you can put together a very simple test of both your REST interface as well as testing your web service through actual browsers (all major browsers are supported).
#!/usr/bin/ruby
#
# Requires that you have installed the following gem packages:
# json, minitest, watir, watir-webdrive, rest-client
# To use Chrome, you need to install chromedriver on your path
require 'rubygems'
require 'rest-client'
require 'json'
require 'pp'
require 'minitest/autorun'
require 'watir'
require 'watir-webdriver'
class TestReportSystem < MiniTest::Unit::TestCase
def setup
#browser = Watir::Browser.new :chrome # Defaults to firefox. Can do Safari and IE too.
# Log in here.....
end
def teardown
#browser.close
end
def test_report_lists # For minitest, the method names need to start with test
response = RestClient.get 'http://localhost:8080/reporter/reports/getReportList'
assert_equal response.code,200
parsed = JSON.parse response.to_str
assert_equal parsed.length, 3 # There are 3 reports available on the test server
end
def test_on_browser
#browser.goto 'http://localhost:8080/reporter/exampleReport/simple/genReport?month=Aug&year=2012'
assert(#browser.text.include?('Report for Aug 2012'))
end
end
Run the test cases by simply executing the script. There are many other testing systems and REST clients for Ruby which can be put to work in a similar way.
You might have a look at this approach http://anthonyeden.com/2013/07/10/testing-rest-apis-with-cucumber-and-rack.html
although many might say that using Cucumber is really more application or Acceptance testing and not unit testing, it does contain an approach to creating the HTTP headers and forming the http request, which I'm guessing might be where you are stuck?
Personally I don't have a problem with that since if you are truely going to unit test the API, you'd likely have to mock any units of code the api might be talking with (e.g. however you are persisting the data)
Seeing as I'm a QA guy not a dev, I'd be perfectly happy with using cucumber and testing it at that level, but I also greatly appreciate it when devs unit test, so while you might use rSpec instead of Cuke, perhaps the tip towards 'rack test' will be useful to what you are trying to accomplish.
You can try using airborne which is a framework written for just this purpose:
https://github.com/brooklynDev/airborne
You can test against either a live API, or against a Sinatra, Grape, Rails application.
I would use fakeweb gem to do unit testing with web services.
I would suggest client-api gem - it has loads of useful features specific to api automation which is easy to use and to maintain scripts.
https://github.com/prashanth-sams/client-api
Interestingly, this gem binds an api automation framework within itself. So, you don't even need a framework setup.
Key Features of client-api library:
Custom Header, URL, and Timeout support
URL query string customization
Datatype and key-pair value validation
Single key-pair response validation
Multi key-pair response validation
JSON response schema validation
JSON response content validation
JSON response size validation
JSON response is empty? validation
JSON response has specific key? validation
JSON response array-list sorting validation (descending, ascending)
Response headers validation
JSON template as body and schema
Support to store JSON responses of each tests for the current run
Logs support for debug
Custom logs remover
Auto-handle SSL for http(s) schemes
Example specs: https://github.com/prashanth-sams/client-api/tree/master/spec/client
Add this config snippet in the spec_helper.rb file:
ClientApi.configure do |config|
config.base_url = 'https://reqres.in'
config.headers = {'Content-Type' => 'application/json', 'Accept' => 'application/json'}
config.basic_auth = {'Username' => 'ahamilton#apigee.com', 'Password' => 'myp#ssw0rd'}
config.json_output = {'Dirname' => './output', 'Filename' => 'test'}
config.time_out = 10 # in secs
config.logger = {'Dirname' => './logs', 'Filename' => 'test', 'StoreFilesCount' => 2}
end
RSpec test scenarios look like,
api = ClientApi::Api.new
it "GET request" do
api.get('/api/users')
expect(api.status).to eq(200)
expect(api.message).to eq('OK')
end
it "POST request" do
api.post('/api/users', {"name": "prashanth sams"})
expect(api.status).to eq(201)
end
Note: This is an active project handling issues and new features based on user requirements

How do I create a Ruby SOAP client without using a WSDL?

I need to write a soap client that is capable of sending and receiving soap messages.
This soap service does not have an associated WSDL file and soap4r and savon both seem to require one.
I have an example of what I need to do in Java, see the link below.
http://community.cecid.hku.hk/index.php/product/article/writing_hermes_2_ws_client_under_java/#ebms-2_0-sender-ws
I could use java for this, at this point it seems like it would be easier. However I personally prefer coding in ruby and our company has more ruby resources than java.
Can anyone confirm thats its possible to do something similar to java example in ruby without writing my own specialised soap library?. I need to be able to send a payload, which I believe is usually in the form of a soap attachment.
I am particularly interested in seeing soap4r examples that don't use a WSDL as I have had trouble finding any with google.
Any help much appreciated.
as of Savon v2, the syntax is slightly different
client = Savon.client do
endpoint "http://example.com"
namespace "http://v1.example.com"
end
http://savonrb.com/version2/client.html
Savon does not require a WSDL document. Please take a look at the new documentation. If you know the SOAP endpoint and target namespace, you can execute a SOAP request like this:
client = Savon::Client.new
wsdl.endpoint = "http://example.com"
wsdl.namespace = "http://soap.example.com"
end
client.request :any_soap_action do
soap.body = { :do => "something" }
end
client = Savon::Client.new
wsdl.endpoint = "http://example.com"
wsdl.namspace = "http://soap.example.com"
end
This does not work, it misses a the block name and the "e" in namespace:
client = Savon::Client.new do | wsdl |
wsdl.endpoint = "http://example.com"
wsdl.namespace = "http://soap.example.com"
end

how can I capture response from twitter.com? ( ruby + twitter gem)

how can I capture response from twitter.com? To make sure that everything went ok?
I am using ruby and ruby twitter gem and the my code is basically like that
oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
oauth.authorize_from_access('access token', 'access secret')
client = Twitter::Base.new(oauth)
client.update('Heeeyyyyoooo from Twitter Gem!')
The update twitter api method will send back a response that will let you know if everything went okay. It can respond in either json or xml, I'm sure the twitter gem is using one or the other as a default. You need to save the return value to a variable and parse it, if you have a status id in there then it worked. Try using a token or secret to check what happens when it errors. I would suggest changing your last line to this
ret = client.update('Heeeyyyyoooo from Twitter Gem!')
and then add this line below that to check out what you got back
puts ret.inspect
or
logger.info ret.inspect
or your choice of logging method
[Edit]
It looked like the twitter gem hides the twitter api's actual response from you, parses it for you and just returns you the relevant bits. in the case of the update method it just returns you the id of your new tweet. you can view the id like this
puts ret.id
If you use another library to connect to the twitter api and need to parse xml or json responses then then the rest of this answer may be what you are looking for.
[/Edit]
If you are not using a gem that parses twitter api responses for you then you will need to use something to parse the twitter api's responses into data that you can do something with. There are tons of ways to do this depending on what format you want to parse (json or xml)
My preferences:
XML : Hpricot : gem install hpricot : http://github.com/hpricot/hpricot
json : json : gem install json : http://github.com/flori/json
Here is more information on what the twitter api update method returns: http://apiwiki.twitter.com/Twitter-REST-API-Method:-statuses%C2%A0update
This worked for me...
begin
resp = Twitter.update(params[:message])
rescue Exception => e
# e.message contains the twitter response
end

Issues POSTing XML to OAuth and Signature Invalid with Ruby OAuth Gem

[Cross-posted from the OAuth Ruby Google Group. If you couldn't help me there, don't worry bout it]
I'm working on integrating a project with TripIt's OAuth API
and am running into a weird issue.
I authenticate fine, I store and retrieve the token/secret for a given
user with no problem, I can even make GET requests to a number of
services using the gem. But when I try using the one service I need
POST for, I'm getting a 401 "invalid signature" response.
Perhaps I'm not understanding how to pass in data to the AccessToken's
post method, so here's a sample of my code:
xml = <<-XML
<Request>
<Trip>
<start_date>2008-12-09</start_date>
<end_date>2008-12-27</end_date>
<primary_location>New York, NY</primary_location>
</Trip>
</Request>
XML`
response = access_token.post('/v1/create', {:xml => xml},
{'Content-Type' => 'application/x-www-form-urlencoded'})
I've tried this with and without escaping the xml string before hand.
The guys at TripIt seemed to think that perhaps the xml param wasn't
getting included in the signature_base_string, but when I output that
(from lib/signature/base.rb) I see:
POST&https%3A%2F%2Fapi.tripit.com%2Fv1%2Fcreate&oauth_consumer_key
%3D%26oauth_nonce
%3Djs73Y9caeuffpmPVc6lqxhlFN3Qpj7OhLcfBTYv8Ww%26oauth_signature_method
%3DHMAC-SHA1%26oauth_timestamp%3D1252011612%26oauth_token
%3D%26oauth_version%3D1.0%26xml%3D%25253CRequest%25253E
%25250A%252520%252520%25253CTrip%25253E%25250A
%252520%252520%252520%252520%25253Cstart_date%25253E2008-12-09%25253C
%252Fstart_date%25253E%25250A
%252520%252520%252520%252520%25253Cend_date%25253E2008-12-27%25253C
%252Fend_date%25253E%25250A
%252520%252520%252520%252520%25253Cprimary_location%25253ENew
%252520York%252C%252520NY%25253C%252Fprimary_location%25253E%25250A
%252520%252520%25253C%252FTrip%25253E%25250A%25253C%252FRequest%25253E
%25250A
This seems to be correct to me.
I output signature (from the same file) and the output doesn't match
the oauth_signature param of the Auth header in lib/client/
net_http.rb. It's been URL-encoded in the auth header. Is this
correct?
Anyone know if the gem is broken/if there's a fix somewhere? I'm finding it hard to trace through some of the code.
Your oauth_token is empty. Not familiar with the protocol, is that ok?
Once you include the correct token, please also remember to use token_secret in the signing.

Resources