Am a newbie to ruby. I am trying to invoke a REST API from ruby code. I have tried the code with both as standalone ruby code and inside a application using sinatra. But am facing same issue every where. Below are the options I have tried.
My Code to Invoke Post API using RestClient. Have modified the data to make it generic
url="https://myapiurl.com/endpointname"
person={"name"=>"Sample Name","age"=>"20"}
headers={
"Content-Type"=>"application/json",
"api-key"=>"ABCDEFGHIJKL"
}
response=RestClient.post url,person.to_json,headers
puts response
I wrote the above block of code in a function and tried calling. But I got response as below
{"status": 401, "error":"Unauthorized Access"}
I tried the same api via postman with below settings and was able to get a proper response from the api.
URL : https://myapiurl.com/endpointname
Headers : Content-Type: application/json, api-key:"ABCDEFGHIJKL"
Body: Raw:application/json: {"name":"Sample Name","age":"20"}
When I tried not passing api-key
in the headers via postman I got similar response as I got via ruby code.
Next I tried generating code from postman option. Below is the code that got generated from postman for Ruby(Net::Http).
I removed the post params of cache-control
and postman-token
from the ruby code and tried running the ruby code. Again I got the same 'Unauthorized' response only !
require 'uri'
require 'net/http'
url = URI("https://myapiurl.com/endpointname")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/json'
request["api-key"] = 'ABCDEFGHIJKL'
request["cache-control"] = 'no-cache'
request["postman-token"] = 'some value got generated'
request.body = "{\"name\":\"Sample Name\",\"age\":\"20\"}"
response = http.request(request)
puts response.read_body
I suspected is it some IP level issue is blocking hence tried used curl command to hit the api as below. I got proper response from the API.
curl -X POST \
https://myapiurl.com/endpointname \
-H 'content-type: application/json' \
-H 'api-key: ABCDEGHIJKL' \
-d '{"name":"Sample Name","age":"20"}'
I believe that the api-key
is not getting passed to the request via the ruby code. Is my way of sending the api-key
in headers via ruby code correct?