34

I have the rest client gem and I am defining a request like this:

url = 'http://someurl'
request =  {"data" => data}.to_json
response = RestClient.post(url,request,:content_type => :json, :accept => :json)

However I need to set the HTTP header to something. For example an API key. Which could be done in curl as:

curl -XHEAD -H x-auth-user: myusername -H x-auth-key: mykey "url"

Whats the best way to do this in ruby? Using this gem? Or can I do it manually to have more control.

Charlie Davies
  • 1,814
  • 4
  • 29
  • 50

4 Answers4

51

The third parameter is the headers hash.

You can do what you want by:

response = RestClient.post( 
  url, 
  request,
  :content_type => :json, :accept => :json, :'x-auth-key' => "mykey")
gene_wood
  • 1,960
  • 4
  • 26
  • 39
Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
22

You can also do this

RestClient::Request.execute(
   :method => :get or :post,
   :url => your_url,
   :headers => {key => value}
)
rrrrong
  • 371
  • 2
  • 4
4

I had the same problem with Rest-Client (1.7.2) I need to put both params and HTTP headers.

I solved with this syntax:

params = {id: id, device: device, status: status}
headers = {myheader: "giorgio"}

RestClient.put url, params, headers

I hate RestClient :-)

Giorgio Robino
  • 2,148
  • 6
  • 38
  • 59
0

If PUT isn't allowed we can pass it in the header of POST. Headers in bold. This worked for me:

act_resp = RestClient.post url, req_param, **:content_type => :json, :method => :put**

armatita
  • 12,825
  • 8
  • 48
  • 49
Serhii Aksiutin
  • 619
  • 6
  • 7