Charles Duporge
Charles Duporge

Reputation: 672

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.

Upvotes: 16

Views: 23721

Answers (3)

lisyk
lisyk

Reputation: 91

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.

Upvotes: 5

Gokul
Gokul

Reputation: 3231

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

Upvotes: 28

Jayaprakash
Jayaprakash

Reputation: 1403

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.

Upvotes: 6

Related Questions