How to use external API in Ruby in Rails - ruby-on-rails

I need to use an external API in my app in order to have companies informations. Beginning and having never used API in ruby, I don't know where to start. Maybe there is a gem for it but I have found 2 API that returns me JSON : https://datainfogreffe.fr/api/v1/documentation and https://firmapi.com/ (they're in french sorry about that).
Does someone have a good tutorial or hints to help me begin ?
The final need is to retrieve companies datas just by giving the company ID.

You can use Net::HTTP to call APIs in Ruby on Rails.
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
request.body = {} # SOME JSON DATA e.g {msg: 'Why'}.to_json
response = http.request(request)
body = JSON.parse(response.body) # e.g {answer: 'because it was there'}
http://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTP.html

You can use gem for calling REST APIs in ruby.
Also, if you want to find any ruby gem for any purpose you can have a look at this.
You can have a look at this to get company details.

You need to use HTTP client library. There are a few popular libraries:
HTTParty
Faraday
Built-in Net::HTTP
Rest-Client
HTTPClient
You can take a look and compare them on Ruby Toolbox:
https://www.ruby-toolbox.com/categories/http_clients
Faraday is the most popular one. But it is the heaviest also because it covers most cases. So check documentation for each and depending on your task pick one that works the best.

Related

Replacement of HTTParty.send with Faraday

I am rails beginner working on a task to replace HTTParty with Faraday. So in codebase I call put/post/get based on the verb like so:
response = HTTParty.send(verb, url, http_options)
I am aware that Faraday provides an option to call them individually like so:
Faraday.put(url) do |req|
Can I somehow abstract it, to call based on the verb.
Please let me know, if I can answer any questions.

Reading JavaScript variable in Ruby through curl request

I need to read the GBP rate from this javascript file: http://cdn.shopify.com/s/javascripts/currencies.js. I want to be able to get the js variable as JSON so that I can easily access the variable I need with its index. I tried a couple of ways as follows with eventually no success.
Way 1
Source: https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html
My code:
uri = URI('http://cdn.shopify.com/s/javascripts/currencies.js')
#response = Net::HTTP.get(uri) # => String
Result: I get the result as a string and reading the GBP rate from the string is difficult and probably not the correct way.
Way 2
Source: curl request in ruby
My Code:
url = 'http://cdn.shopify.com/s/javascripts/currencies.js'
mykey = 'demo'
uri = URI(url)
request = Net::HTTP::Get.new(uri.path)
request['Content-Type'] = 'application/xml'
request['Accept'] = 'application/xml'
request['X-OFFERSDB-API-KEY'] = mykey
#response = Net::HTTP.new(uri.host,uri.port) do |http|
http.request(request)
end
Result: This returns me Net::HTTP:0x007f2480874050 which looks like a memory address, definitely not what I want.
In addition, I've included require 'net/http', require 'json' in my controller in either case.
I am very new to Ruby and I don't know how to figure this out. So looking for someone who can help.
This is a bit of a weird request, IMO, but Rails can do it. Rails comes with a library called execjs automatically, which lets you run javascript from ruby. So, you have some javascript you want to run in that file, but you also want to return specific key from that javascript, so something like this should do it:
# Expanding upon 'Way 1', which got you the javascript as a string
uri = URI('http://cdn.shopify.com/s/javascripts/currencies.js')
response = Net::HTTP.get(uri)
gbp_rate = ExecJS.exec "#{response}; return Currency.rates.GBP;"
p gbp_rate # => 1.40045
I just want to reiterate (from their FAQ in the README) though:
Can ExecJS be used to sandbox scripts?
No, ExecJS shouldn't be used for any security related sandboxing. Since runtimes are automatically detected, each runtime has different sandboxing properties. You shouldn't use ExecJS.eval on any inputs you wouldn't feel comfortable Ruby eval()ing.
This file looks safe, but just keep it in mind, you are actually executing this javascript.
Personally, I would look to see if there's an API somewhere that can give you this value more easily, or if it doesn't change often (I have never used Shopify so don't know how much this changes) just hardcode it in the app as a config value and update it manually. Just feels cleaner, to me.

Ruby library with least footprint to host a very simple single endpoint API

I have a very simple number crunching Ruby function that I want to make available via a web API. The API is essentially a single endpoint, e.g. http://example.com/crunch/<number> and it returns JSON output.
I can obviously install Rails and implement this quickly. I require no more help from a 'framework' other than to handle HTTP for me. No ORM, MVC and other frills.
On the far end, I can write some Ruby code to listen on a port and accept GET request and parse HTTP headers etc. etc. I don't want to re-invent that wheel either.
What can I use to expose a minimal API to the web using something with the least footprint/dependencies. I read about Sinatra, Ramaze, etc., but I believe there can be a way to do something even simpler. Can I just hack some code on top of Rack to do what I am trying to do?
Or in other words, what will be the simplest Ruby equivalent of the following code in nodejs:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var ans = crunch(number);
res.end(ans);
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
You seem like you want to use Rack directly. "Rack from the Beginning" is a decent tutorial that should get you started.
It'll probably look something like this:
class CrunchApp
def self.crunch(crunchable)
# top-secret crunching
end
def self.call(env)
crunchy_stuff = input(env)
[200, {}, crunch(crunchy_stuff)]
end
private
def self.input(env)
request = Rack::Request.new(env)
request.params['my_input']
end
end
Rack::Server.start app: CrunchApp
But I must say, using that instead of something like Sinatra seems silly unless this is just a fun project to play with things. See their 'Hello World':
require 'sinatra'
get '/hi' do
"Hello World!"
end
Ruby-Grape is a good option for your use case. It has a minimal implementation over Rack that allow the creation of simple REST-API endpoints.
Cuba is another good option with a thin layer over Rack itself.sample post
If you are familiar with Rails you can use the Rails API gem which is very well documented with minor overhead. Remember also that Rails-API will be part of Rails 5.
Last, but not last you can implement it on Rack directly.

Any Gem that helps to get the http status of the specified URL in Rails

There are number of URLs that I want to test and want to know the HTTP status of each of these URLs without hitting them in browser.
does anyone has idea about the gem, which can help me to find the solution?
How about standard Ruby, no extra gems (just require 'net/http'):
Net::HTTP.new('google.com').head('/').code
#=> "301"
If for some reason you want to do more than a head request, replace head with get.
I'm pretty sure you could achieve this with standard ruby (Net::HTTP and friends). However there are many gems to handle stuff like that. I have a bias towards Typhoeus.
Example :
Typhoeus::Request.get('http://google.fr').code
=> 301
use HTTParty:
uri = "http://url.to.inspect"
request = HTTParty.get( uri )
return true if request.code.to_i == 200

Rails 1.x client talking to RESTful server

Hey all, I've got a client that is integrating a Rails 1.2.6 site with another site that exposes services RESTfully. Upgrading to Rails 2.x is not an option at this time. Does anyone have recommendations for methods other than direct Net::HTTP calls to communicate with the REST service? Techniques or Gem recommendations are welcome, but most of the gems I've seen seem to have a dependency on ActiveSupport 2.x, which I understand to be incompatible with Rails 1.x.
Thanks in advance for any input you can provide.
Try HTTParty. It's very light on the dependencies, and makes it braindead-easy to add consumption of JSON or XML resources to an application.
Thanks Chris Heald for your response. I did end up using Net::HTTP because it was more straightforward than I thought it was in the end. HTTParty looks like it could make this easier still, but for the benefit of future people with this problem, here's what I did.
# Assume #user_name and #password were previously declared to be the
# appropriate basic auth values and that the connection is open as #connection
def put(path, body, header={})
request = Net::HTTP::Put.new(path, header.merge({'Accept' => 'application/xml,application/json', 'Content-type'=>'application/json'}))
request.basic_auth(#user_name, #password)
#connection.request(request, body).body
end
def post(path, body, header={})
request = Net::HTTP::Post.new(path, header.merge({'Accept' => 'application/xml,application/json', 'Content-type'=>'application/json'}))
request.basic_auth(#user_name, #password)
#connection.request(request, body).body
end
def get(path, header={})
request = Net::HTTP::Get.new(path)
request.basic_auth(#user_name, #password)
#connection.request(request).body
end
I then called JSON::parse() on the output of these methods and got a hash representing the JSON that I could use as I saw fit.

Resources