4

I'm trying to learn Ruby for the first time. I have some experience in PHP and in PHP, I made a function like

function call_api(endpoint,method,arr_parameters='')
{
 // do a CURL call
}

Which I would use like

call_api('https://api.com/user','get','param=1&param=2');
call_api('https://api.com/user/1','get');
call_api('https://api.com/user/1','post','param=1&param=2');
call_api('https://api.com/user/1','put','param=1&param=2');
call_api('https://api.com/user/1','delete');

So far, I've only learned how to do a GET and POST call with Ruby like so:

  conn = Net::HTTP.new(API_URL, API_PORT)
  resppost = conn.post("/user", 'param=1', {})
  respget = conn.get("/user?param=1",{})

But I don't know how to do a delete and put. Can someone show sample code for the delete and put calls with the Net::HTTP object?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
John
  • 32,403
  • 80
  • 251
  • 422
  • 1
    There are a number of very good HTTP gems for Ruby, in particular there's Curb which is a well-tested wrapper for libCurl. https://www.ruby-toolbox.com/categories/http_clients has a good list and, instead of trying to roll your own, it's better to take advantage of the work the others have done. – the Tin Man Oct 10 '14 at 21:39
  • 1
    Net::HTTP is quite poorly designed and breaks a lot of Ruby conventions in my opinion. I second @theTinMan and recommend using a different http client library if you can – JKillian Oct 10 '14 at 21:54
  • hey John did my answer help? – Anthony Oct 13 '14 at 17:25

4 Answers4

3

You would just namespace it:

Net::HTTP::Put.new(uri)

Same with delete:

Net::HTTP::Delete.new(uri)

You can even do that with your existing calls:

conn = Net::HTTP.new(uri)
con.get(path)

that is equivalent to:

Net::HTTP::Get.new(uri)
Anthony
  • 15,435
  • 4
  • 39
  • 69
3

For DELETE you can use conn.delete("/user/1", {}) or

request = Net::HTTP::Delete.new("/user/1")
response = conn.request(request)

For PUT,

response = http.set_request('PUT', "/user/1", "param=1") 

or Net::HTTP::Put.new(path)

rohit89
  • 5,745
  • 2
  • 25
  • 42
3

I like the Faraday gem. I find its design the simplest.

Once you gem install faraday you can require 'faraday' and do:

result = Faraday.get('http://google.es')

You can also POST, PUT, DELETE, etc.

Faraday.delete('http://google.es')
Faraday.post('http://google.es', {some_parameter: 'hello'})

Project: https://github.com/lostisland/faraday

Nerian
  • 15,901
  • 13
  • 66
  • 96
1

Can I suggest a look at httparty? They offer some really awesome examples right on their page to do exactly what you want to do.

response = HTTParty.get('https://api.stackexchange.com/2.2/questions?site=stackoverflow')

puts response.body, response.code, response.message, response.headers.inspect

And many more examples of calling different endpoints.

Jeff Ancel
  • 3,076
  • 3
  • 32
  • 39