2

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.

Satchel
  • 16,414
  • 23
  • 106
  • 192
  • Are you sure the url you created is correct? Meaning does the value replaced by NUMBER and APIKEY equal what you expect? – Max Oct 01 '14 at 04:38
  • Yeah the number is right, I figured it out...hardcoding the JSON formatting was the error. – Satchel Oct 02 '14 at 19:19
  • One possibility is that the RestClient adds some headers that your API does not accept. Looking the source code, it does seem to add some default headers: `{:accept => '*/*; q=0.5, application/xml', :accept_encoding => 'gzip, deflate'}`. Do you need to use this library? There are many other libraries out there you can use to make http requests. – Max Oct 03 '14 at 02:35
  • I liked RestClient for some reason in the past...but I think I figured it out....I actually needed to use I believe a .to_json method and not use the format above and they were able to process it. – Satchel Oct 04 '14 at 04:41

1 Answers1

1

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"}
Hellfar
  • 393
  • 2
  • 17