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.