1

I'm trying to work with a 3rd party API that requires an array to be sent within a POST request body. I've already gotten the hang of sending JSON; I've read you just need to set some headers and call to_json on the POST body. However, I'm not sure how to embed an array within that POST body. I've tried the following:

HTTParty.post(url, 
    :body => { 
        :things => [{:id => 1}, {:id => 2}, {:id => 3}],
    }.to_json,
    :headers => { 
        'Content-Type' => 'application/json', 
        'Accept' => 'application/json'
    }
)

but this is giving me a server error, leading me to believe the array isn't being formatted correctly. Could someone please advise on how to send an array within a JSON POST request? Thanks!

EDIT:

The error I get back is the following:

#<HTTParty::Response:0x10 parsed_response=nil, 
@response=#<Net::HTTPInternalServerError 500 Internal Server Error readbody=true>, 
@headers={"error_message"=>["Can not deserialize instance of java.lang.Long out of 
START_OBJECT token  at [Source: org.apache.catalina.connector.CoyoteInputStream@30edd11c; 
line: 1, column: 15] (through reference chain: REDACTED[\"things\"])"], 
"error_code"=>["0"], "content-length"=>["0"], 
"date"=>["Wed, 13 Aug 2014 22:53:49 GMT"], "connection"=>["close"]}> 

The JSON should be in the format:

{ "things" : [ {"id": "..."}, {"id: "..."}, ... ] }
5
  • Your code looks ok in general to me. The JSON will be valid (and will contain an array), but perhaps you are not sending data in the correct structure for the API. Could you give a reference or perhaps a correct example JSON from the API docs? Also, please give server error message in case that is relevant. Commented Aug 13, 2014 at 21:09
  • I've updated the post with what you requested! Also changed my code slightly as I made a mistake the first time around. Commented Aug 13, 2014 at 22:59
  • Is the key :myid deliberate and required? It does not match your example JSON. Commented Aug 14, 2014 at 6:37
  • My bad, that was a typo. But unrelated to the issue. Commented Aug 14, 2014 at 14:04
  • This SO answer might be helpful. Looks like HTTParty uses HashConversions for normalizing a request by default. Try using HTTParty.query_string_normalizer to override this behavior for arrays. Commented Aug 14, 2014 at 16:38

2 Answers 2

1

The simplest way to embed an array within a POST body using HTTParty in Ruby on Rails is to pass the request to an instance variable (any name of your choice can suffice for the instance variable).

So we will have

@mypost = HTTParty.post(url, 
         :body => { 
                    :things => {
                       :id => 1, 
                       :id => 2,
                       :id => 3
                    },
                  }.to_json,
         :headers => { 
                    'Content-Type' => 'application/json',
                    'Authorization' => 'xxxxxxxxxx' 
                    'Accept' => 'application/json'
                    })

Here is an example of an HTTParty Post Request

 @myrequest = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
            :body => {
                        :books => {  
                          :name => "#{@book.name}",
                          :author => "#{@book.author}",
                          :description => "#{@book.description}",
                          :category_id => "#{@book.category_id}",
                          :sub_category_id => "#{@book.sub_category_id}"
                        },
                      }.to_json, 
            :headers => { 'Content-Type' => 'application/json', 
                          'Authorization' => '77d22458349303990334xxxxxxxxxx',
                          'Accept' => 'application/json'})

That's all

I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

-1

I had a similar requirement for a SurveyMonkey API, the below will create a params_hash with nested array of hashes

create the fields array of hashes

fields = []

i =0

while i < 10 do

fields << {":id#{i}" => "some value #{i}"}

i += 1

end

method with optional splat field variable

def get_response(survey_id, respondent_ids, *fields )

  params_hash = {}

  params_hash[:survey_id] = "#{survey_id}"

  params_hash[:respondent_ids] = respondent_ids

  params_hash[:fields] = fields

  @result = HTTParty.post("http://"some.address.here",

    #:debug_output => $stdout,

    :headers => {'Authorization' => "bearer #{@access_token.to_s}", 'Content-type' => 'application/json'},

  :body => params_hash.to_json,

  )

end

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.