EzDevInfo.com

rest-client

Simple HTTP and REST client for Ruby, inspired by microframework syntax for specifying actions. File: README — Documentation for rest-client/rest-client (master)

Testing REST webservices

My organization is working on building RESTful webservices on JBoss appserver. The QA team is used to testing SOAP webservices so far using SoapUI. SoapUI has a new version that has REST capabilities. We're considering using that.

  1. Are there any publicly available RESTful services available on the net for free that someone could test ?
  2. What tools are available(and used) for testing RESTful web services ?

Source: (StackOverflow)

How do I do basic authentication with RestClient?

Does anyone know how to do basic authentication with RestClient?

I need to create a private repository on GitHub through their RESTful API.


Source: (StackOverflow)

Advertisements

How to set timeout in RestClient gem in Ruby?

I am using RestClient gem by making get call to the server through it. The question is how do I set the timeout from client side.

RestClient.get "http://127.0.0.1:7819/tokenize/word/stackoverflow"

I want to set it to 10 seconds.

Thanks in Advance!!


Source: (StackOverflow)

How to handle exceptions with Ruby Rest-Client

I recently switched from Ruby's Net:HTTP class to rest-client 1.6.7.

I find it a lot easier to form requests, but unlike Net:HTTP request, when rest-client gets anything other than a 200, the request dies. I've tried putting a breakpoint directly after the RestClient.get, and it never gets hit - so I'm doing something wrong.

def get_member_using_card
  resource = "#{@settings_app_uri}api/v1/card/#{self.member_card_num}?token=#{@settings.api_key}"
  response = RestClient.get resource
  if response.code == 200 
    card = JSON.parse(response.body)
    self.customer_id = card['card']['customer_id']
  else
    return 0
  end
end

Which results in this stacktrace:

RestClient::ResourceNotFound - 404 Resource Not Found:
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/abstr
act_response.rb:48:in `return!'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:230:in `process_result'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:178:in `block in transmit'
        /Users/tim/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/net/http.rb:627:in `start'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:172:in `transmit'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:64:in `execute'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:33:in `execute'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient.rb:68
:in `get'

Can someone tell me how to properly evaluate the response code and keep this exception from happening...?


Source: (StackOverflow)

How to upload a file using a rest client for node

I have a REST client on node, and I'm trying to upload pdf a file to another REST webserver which provides the ability to parse my pdf and extract some data. Basically it is a service. The npm package that I use is: https://www.npmjs.com/package/node-rest-client. If there are other rest clients, I can use those as well. The rest api I need to use is described below:

POST    /         ; Uploads a new PDF document via a form <br>
POST    /file     ; Uploads a new PDF document via bytestream

The question is how to upload the file. Also, I would like to see how to store the file at the other end.


Source: (StackOverflow)

RestTemplate GET request with request params

I have to call a REST webservice and I am planning to use RestTemplate. I looked at examples on how to make a GET request and they are as shown below.

 String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class,"42","21");

In my case the RESTful url is something like below. How do I use RestTemplate in this case?

http://example.com/hotels?state=NY&country=USA

So my question would be how do I send request parameters for GET requests?


Source: (StackOverflow)

CodeIgniter Passing POST data from RestClient to RestServer API

I've spent my whole day trying to figure out this problem. Posting this issue here is my last hope. I hope someone can help to continue working on my first job.

So, POST works fine when directly passing data from my views to the RestServer directly. However, RESTServer API is not able to find POSTs data sent from the RestClient.

Here are the snippets:

RestClient API:

        $ver = 'v1';
        $config = array('server'          => base_url()."v1",
                        'api_key'         => 'xxxxxx',
                        'api_name'        => 'X-API-KEY',
                        'http_user'       => 'admin',
                        'http_pass'       => 'xxxxx',
                        'http_auth'       => 'basic',
                );

        $this->rest->initialize($config);
        $this->rest->format('application/json');
        $param = array(
                'id' => $this->input->post('id'), // works fine here
                'name' => $this->input->post('name')
                );
        $user = $this->rest->post('employer/postNewProject', $param, 'json');


        //if (isset($user->errors)) show_404('admin');
        $this->rest->debug();

RestServer API

class Employer extends REST_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->lang->load("application");
        $this->load->library("users/auth"); 
        Datamapper::add_model_path( array( APPPATH."modules" ) );
    }

    public function postNewProject_post()
    {  
        // I tired $this->post() and $this->input->post() but both not finding the data
        $message = array("id" => $this->post("id"), "name" => $this->input->post("name"));
        $this->response($message, 200); // 200 being the HTTP response code
    }
}

Results:

Response when using $this->post('id');
{"id":false}

Response when using $this->post();
{"id":[]}

Note: I've replaced the POSTS requests with hardcoded data, and still the RestServer is not able to recieve the data from my RestClient.

If you need me to provide anything else, please ask.

Thank you in advance.


Source: (StackOverflow)

HttpStatus become deprecated in API level 22

Usually I used to check for the server different code responses in my RestClient class using the org.apache.http.HttpStatus class as the following example:

if (HttpStatus.SC_OK == restClient.getResponseCode()) {
            //200 OK (HTTP/1.0 - RFC 1945)
            return true;
} else if (HttpStatus.SC_BAD_GATEWAY == restClient.getResponseCode()){
           //502 Bad Gateway (HTTP/1.0 - RFC 1945)
            return false;
}

But recently the class became deprecated since API level 22 according to the official documentation

This interface was deprecated in API level 22. Please use openConnection() instead. Please visit this webpage for further details.

But using OpenConnection() method for me does not make any sense.

My Question is: Is there any other way to do the same functionality without needing to hardcode all the code responses by myself within the application?

Thanks in advance.


Source: (StackOverflow)

Proper Android REST client [closed]

I made my own REST client library for an Android application, but after watching the Google I/O presentation on the subject I realized I had it all wrong (precisely what they show slide 9).

Now I am looking to do it again the right way, but I'm wondering if there isn't a library that could save me the trouble. We use Jersey on the server side.

I've looked at different solutions : CRest and Resty, but what I'd like to find an Android solution so I don't have to implement the ContentProvider stuff myself, and android-jbridge, but it doesn't look very active.

At this point I'm considering using RestTemplate (from Spring Android) and writing the stuff around it myself, but that'll take some time.

Any better alternative?


Source: (StackOverflow)

Mystifying "undefined constant" issue with Ruby/Rails

I've got a Rails project where a constant is being nuked at some point while serving a request.

I'm using the mime/types and restclient gems. The restclient module defines an extension to MIME which contains the method type_for_extension.

module RestClient
    ...
    def stringify_headers headers
      result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')
      ...
    end
  end
end

module MIME
  class Types
    def type_for_extension ext
      candidates = @extension_index[ext]
      candidates.empty? ? ext : candidates[0].content_type
    end
    class << self
      def type_for_extension ext
        @__types__.type_for_extension ext
      end
    end
  end
end

I can access MIME::Types.type_for_extension on my first invocation of a given controller action. On the second invocation, it's gone.

I can still use MIME::Types.type_for, but the added method is simply gone, so when I try to use the RestClient module it throws an exception on the line showin in stringify_headers:

NoMethodError, message: undefined method `type_for_extension' for MIME::Types:Class

**How is this possible? type_for_extension defined in the same file as stringify_headers; how could the latter get nuked but not the former?


EDIT: FIXED IT!

In my config:

config.gem "aws-s3", :version => ">= 0.6.2", :lib => "aws/s3"  
config.gem 'mime-types', :lib => 'mime/types'

aws-s3 was loading mime-types via require_library_or_gem, which ultimate invoked ActiveSupport::Dependencies.autoload_module! which maintains a table called autoloaded_constants which are nuked when ActionController.close calls Dispatcher.cleanup_application.

Fix was to load mime-types first, so it's not autoloaded.

*whew*


Source: (StackOverflow)

ruby rest-client: make it never timeout?

I am trying to use ruby rest-client to upload a large number of images to a site that I'm writing. My code looks like:

RestClient.post url, :timeout => 90000000, :open_timeout => 90000000, :file_param => file_obj

However, I am getting this error:

RestClient::RequestTimeout: Request Timeout
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.6.1/lib/restclient/request.rb:174:in `transmit'
    from /Library/Ruby/

But when I look at the server log

Completed in 61493ms (View: 2, DB: 1) | 201 Created 

So there doesn't appear to be any reason why this is timing out. Anyone have any idea if there is a timeout param I am not correctly setting?

Thanks


Source: (StackOverflow)

RestClient strips out the array of hashes parameter with just the last hash?

I have a condition where i need to pass a parameter as an array of hashes which looks like this:

The following is the Rack::Test post method for API call.

post "#{url}.json",
:api_key => application.key,
:data => [{"Company"=>"Apple,Inc","Website"=>"Apple.com"},{"Company"=>"Google","Website"=>"google.com"}],
:run => { :title => "The First Run" }

And this is the log of the rails app.

Parameters: {"api_key"=>"6a9acb84d0ea625be75e70a1e04d26360606ca5b", "data"=>[{"Company"=>"Apple,Inc", "Website"=>"Apple.com"}, {"Company"=>"Google", "Website"=>"google.com"}], "run"=>{"title"=>"The First Run"}, "line_id"=>"4e018e2c55112729bd00000a"}

Now, this is the RestClient post method I'm using to call the API.

RestClient.post("/lines/#{@line.id}/runs.json", {:run => {:title => @title}, @param_for_input => @param_data})

And this is the log of the rails app.

Parameters: {"run"=>{"title"=>"run name"}, "data"=>{"Company"=>"Google", "Website"=>"google.com"}, "api_key"=>"f488a62d0307e79ec4f1e6131fa220be47e83d44", "line_id"=>"4e018a505511271f82000144"}

The difference is in the data parameter.

When sending with Rack::Test method, the data is passed as "data"=>[{"Company"=>"Apple,Inc", "Website"=>"Apple.com"}, {"Company"=>"Google", "Website"=>"google.com"}]

but via RestClient way, the parameter data array is stripped out and only the last hash is passed as "data"=>{"Company"=>"Google", "Website"=>"google.com"}

Why the RestClient is stripping out the array of hashes to just a last hash of the array?


Source: (StackOverflow)

How to send multiple asynchronous requests to different web services?

I need to send multiple requests to many different web services and receive the results. The problem is that, if I send the requests one by one it takes so long as I need to send and process all individually.

I am wondering how I can send all the requests at once and receive the results.

As the following code shows, I have three major methods and each has its own sub methods. Each sub method sends request to its associated web service and receive the results;therefore, for example, to receive the results of web service 9 I have to wait till all web services from 1 to 8 get completed, it takes a long time to send all the requests one by one and receive their results.

As shown blew none of the methods nor sub-methods are related to each other, so I can call them all and receive their results in any order, the only thing which is important is to receive the results of each sub-method and populate their associated lists.

private List<StudentsResults> studentsResults = new ArrayList();
private List<DoctorsResults> doctorsResults = new ArrayList();
private List<PatientsResults> patientsResults = new ArrayList();

main (){
    retrieveAllLists();
}

retrieveAllLists(){

     retrieveStudents();
     retrieveDoctors();
     retrievePatients();
}

retrieveStudents(){

    this.studentsResults = retrieveStdWS1();   //send request to Web Service 1 to receive its  list of students
    this.studentsResults = retrieveStdWS2();  //send request to Web Service 2 to receive its  list of students
    this.studentsResults = retrieveStdWS3(); //send request to Web Service 3 to receive its  list of students

}

retrieveDoctors(){

   this.doctorsResults = retrieveDocWS4();   //send request to Web Service 4 to receive its list of doctors
   this.doctorsResults = retrieveDocWS5();  //send request to Web Service 5 to receive its  list of doctors
   this.doctorsResults = retrieveDocWS6(); //send request to Web Service 6 to receive its  list of doctors

}

retrievePatients(){

   this.patientsResults = retrievePtWS7();   //send request to Web Service 7 to receive its list of patients
   this.patientsResults = retrievePtWS8();  //send request to Web Service 8 to receive its list of patients
   this.patientsResults = retrievePtWS9(); //send request to Web Service 9 to receive its list of patients

}

Source: (StackOverflow)

Is the rest client app design approach in google io 2010 still up to date?

two years past, there comes fragment, intent service, cursor loader. Is the approach still up to date, or is there any better or mature pattern to design an android rest client, especially compare to the option B (I don't have the privilege to post image, instead the image could be found from this post).

I know the content provider part is essential. what about the service helper and service component? Up till now, the startService method is a nature of Context or its subclasses. which means the service helper would be an activity. So is it elegant to initiate an activity from a content provider, or should it be initiate from the activity on the top.

  • for those of you who digged into the google io 2011 iosched app source code, will you consider the static class SyncStatusUpdaterFragment in HomeActivity as the service helper, though it couldn't start the SyncService, but it does listen to the call back from SyncService and trigger refresh of UI. So could it be seen as a variance of the Virgil Dobjanschi's approach?

There comes service, intent service, asyncTask and thread. In my opinion, the intent service is suitable for sync of mega pack of data from remote server. That why they use it in the iosched. But the common scenario is that only a part of items will be synchronized with the remote server. So the intent service is too heavy. even the service approach. could we just use the asyncTask or thread in the content provider or some component of that to accomplish this kind of task. Or is there any convincing reason to use the service, and go through the service helper-service-processor path. I am talking about a serious application.

so what's you opinion?


Source: (StackOverflow)

How to handle RestClient::ServerBrokeConnection

I am using the latest version of rest-client gem and upon external access I see a lots of RestClient::ServerBrokeConnection errors, how should I handle this?

The following call fails

response = RestClient::Request.execute(method: :post, url: url, headers: headers, "Content-Type" => "application/x-www-form-urlencoded")

Source: (StackOverflow)