0

I have a rails app that I need to connect to an external RESTful API (not another rails app) and I got the basic get request to work in js which is the following:

<h1>JavaScript in Body</h1>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {

   var method = "GET";
   var url = "https://api.appery.io/rest/1/db/collections/Menu/";
   var header = "X-Appery-Database-Id: 5476a8c5e4b05e4a44a69b0e";
   var response = "response";
   var xhr = new XMLHttpRequest();
   xhr.open(method, url);
   xhr.setRequestHeader("X-Appery-Database-Id", "5476a8c5e4b05e4a44a69b0e");
   xhr.send(null);

   // subscribe to this event before you send your request.
   xhr.onreadystatechange = function() {
     if (xhr.readyState === 4 && xhr.status === 200) {
       response = xhr.responseText;
       document.getElementById("demo").innerHTML = response;
     }
   } 
}
</script>

</body>
</html> 

Now what I have in my rails app is the following for my item.rb

class Item < ActiveResource::Base
   self.site = "https://api.appery.io/rest/1/db/collections/Menu/"
end

and in my show.html.erb i have:

<% provide(:title, @user.name) %>
<% require 'active_resource' %>
<div class="row">
    <aside class="col-md-4">
    <section class="user_info">
        <h1>
            <% item = Item.all %>
            <%= item.first %>
        </h1>
        </section>
    </aside>
</div>

I get the following error:

Failed. Response code = 400. Response message = Bad Request.

which kind of makes sense since I haven't included the headers but I am not sure how to do that. The activeresource page doesn't have any examples about adding headers and I am not sure if you can just do self.header = "my header here". Should I even be using activeresource or should I use something like restclient or can I just use the javascript I have working and add it in my app? Any help is much appreciated.

1 Answers1

1

Not sure exactly what you are looking for here. Is it any reason to make the API call from the javascript? If you have all the info on the controller side, you can use RestClient to make an easy call:

response = RestClient.post( 
  "https://api.appery.io/rest/1/db/collections/Menu/", 
  nil,
  :content_type => :json, :accept => :json, 
  :'X-Appery-Database-Id' => "5476a8c5e4b05e4a44a69b0e")

You can then parse the response, and send to the view what it needs.

Martin
  • 7,634
  • 1
  • 20
  • 23
  • Thank you. I only put the js code because that is what I want to accomplish in rails but i didn't know how to do it. I could do the same for a get correct? something like this `response = RestClient.get...` ?? – blanc0america02 Feb 28 '15 at 19:32
  • Yep, same with Get. Look at RestClient full doc there: https://github.com/rest-client/rest-client – Martin Mar 01 '15 at 13:55