Search code examples
rubynet-http

Ruby example of Net::HTTP for GET, POST, PUT, DELETE


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?


Solution

  • 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)