Reputation: 16724
I am trying to use RestClient to do the following which is currently in Curl:
curl -H "Content-Type: application/json" -X POST --data '{"contacts" : [1111],"text" : "Testing"}' https://api.sendhub.com/v1/messages/?username=NUMBER\&api_key=APIKEY
I don't see in the docs for RestClient how to perform the equivalent as "--data" above as well as passing -H (Header) information.
I tried the following:
url = "https://api.sendhub.com/v1/messages/?username=#{NUMBER}\&api_key=#{APIKEY}"
smspacket = "{'contacts':[#{contact_id}], 'text' : ' #{text} ' }"
RestClient.post url , smspacket, :content_type => 'application/json'
But this give me a Bad Request error.
Upvotes: 2
Views: 1238
Reputation: 411
I presume this is probably very late, but for the record and since I was hanging around with my own question.
Your problem weren't really with the use or not of the :to_json
method, since it will output a string anyway. The body request has to be a string.
According to http://json.org strings in json have to be defined with "
and not with '
, even if in javascript we mostly used to write json this way. Same if you use no quote at all for keys.
This is probably why you received a bad request.
pry(main)> {"test": "test"}.to_json
"{\"test\":\"test\"}"
pry(main)> JSON.parse(RestClient.post('http://httpbin.org/post', "{'test': 'test'}", {content_type: :json, accept: :json}).body)["json"]
nil
pry(main)> JSON.parse(RestClient.post('http://httpbin.org/post', '{test: "test"}', {content_type: :json, accept: :json}).body)["json"]
nil
pry(main)> JSON.parse(RestClient.post('http://httpbin.org/post', '{"test": "test"}', {content_type: :json, accept: :json}).body)["json"]
{"test"=>"test"}
Upvotes: 1