Search code examples
ruby-on-railsapiruby-on-rails-4

How to use external API in 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.


Solution

  • 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