0

I am making the following API GET request, using ruby 1.9.3 and the httparty gem:

uri= HTTParty.post("www.surveys.com/api/v2/contacts",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/json' },
:body => {
  "custom_test" => test,
  "name" => firstname,
  "email" => emailaddress
}

)

The variables auth,test,firstname, and emailaddress are valid. This is the response I am receiving back from my request:

{
  "code": "invalid_json",
  "description": "Request sent with Content-Type: application/json but was unable to decode request body as valid json.",
  "success": false
}
500
#<Net::HTTPInternalServerError:0x007fe4eb98bde0>

What is wrong with the way I am posting this JSON request?

EDIT: It's probably worth noting that the API allows you to define custom attributes to a contact, hence the "custom_test" attribute in the body.

Luigi
  • 5,443
  • 15
  • 54
  • 108
  • Are you sure the API isn't throwing that because it's missing some piece of non-optional data in your request? You should try posting that to a local web server and capturing the output, because your code looks correct to me. – Sean H Aug 20 '13 at 19:24

2 Answers2

4

Since you are receiving an internal server error (500) instead of a not accepted (406), most likely there is coding problem on the server, because an exception that he is not expecting is happening instead of delivery to you a nice error explaining what is wrong (and this would be my first guess).

But let's say it is a problem with the JSON communication. Maybe you have to specify that you are accepting json format?

Try

:headers => { 'ContentType' => 'application/json', 'Accept' => 'application/json' },

Accept header definition from w3:

The Accept request-header field can be used to specify certain media types which are acceptable for the response. Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image.

And content-type header definition:

The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.

fotanus
  • 19,618
  • 13
  • 77
  • 111
  • I believe it as an issue with the server as well. I have passed the information along to the development team to look at it on their end. Thanks for the help, and +1 for the accept header definition- Learn something new everyday. – Luigi Aug 20 '13 at 20:00
2

You're sending a regular HTTP query string while saying it's json. From HTTParty manual: "body: The body of the request. If it‘s a Hash, it is converted into query-string format, otherwise it is sent as-is."

Try:

:body => JSON.generate({
  "custom_test" => test,
  "name" => firstname,
  "email" => emailaddress
})

You need to require 'JSON'

jaeheung
  • 1,208
  • 6
  • 7