How to do a HTTP API call in ruby on rails?

We can do the HTTP API call quite easily and there are multiple ways of doing it. In our example, we are going to do it Net library of the ruby language. When we set up rails this library comes with it.

Following is the code to do an HTTP API call in Ruby on Rails.

How to do a POST call in rails?

uri = URI.parse('Your URL goes here')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

# Set HTTP content type
request = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})

# Set the HTTP post data
data = { email: email, fullName: name }
request.body = data.to_json
response = http.request(request)

# Get response only if it is successful 
response.code == "200" ? response.body : ""

How to do a GET call in rails?

url = URI.parse('Your URL goes here')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
  http.request(req)
}
res.code == "200" ? res.body : ""
Share