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.

4
  • Are you sure the url you created is correct? Meaning does the value replaced by NUMBER and APIKEY equal what you expect?
    – Max
    Commented Oct 1, 2014 at 4:38
  • Yeah the number is right, I figured it out...hardcoding the JSON formatting was the error.
    – Satchel
    Commented Oct 2, 2014 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
    Commented Oct 3, 2014 at 2: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
    Commented Oct 4, 2014 at 4:41

1 Answer 1

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"}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.