Search code examples
ruby-on-rails-4http-headersruby-grapegrape-api

How can I pass headers in grape?


How can I pass headers in grape with post method?

I am passing the header as follows. This method is not working.

resource :pay do
  post :new_order do
    key = header("#{params[:key]}")
    sign = header("#{params[:sign]}") 
    method = params[:method]
    nonce = DateTime.now.to_i
    order_type = params[:type]
    rate = params[:price]
    quantity = params[:amount]

    HTTParty.post("https://www.coins-e.com/api/v2/market/WDC_BTC/")
  end
end

The above API call is for click here

I passed the post request dynamically in chrome rest client. It gives the correct response. Check with

Method: post

Url: https://www.coins-e.com/api/v2/market/LTC_BTC/

Headers:

key :ba57bca64f2adf4721dfd972392321608c38a955370f8349e11f679d

sign:551a7b9a02a4e3ad811cb9f40546135879978e18f1e35f3414410d77a2fdff183941f0593b913695eae18d9236eb3466e01e01026ffb95411e66042078d918a1

Body:

method=neworder&nonce=1403675015&order_type=buy&rate=0.002312&quantity=0.002312


Solution

  • You need to use the HTTParty gem for that.

    For this example you don't need to use headers, you can use query param:

    HTTParty.post("https://www.coins-e.com/api/v2/market/WDC_BTC/",
        :query => { :key => "ba57bca64f2adf4721dfd972392321608c38a955370f8349e11f679d", :sign => "551a7b9a02a4e3ad811cb9f40546135879978e18f1e35f3414410d77a2fdff183941f0593b913695eae18d9236eb3466e01e01026ffb95411e66042078d918a1" })
    

    But if you need to use headers, you can code like that:

    HTTParty.post("https://www.coins-e.com/api/v2/market/WDC_BTC/",
        :headers => { "HeaderExample" => "THISISMYAPIKEYNOREALLY"})