Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

net-http

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?

like image 923
John Avatar asked Oct 28 '25 04:10

John


1 Answers

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)
like image 101
Anthony Avatar answered Oct 29 '25 18:10

Anthony