简体   繁体   中英

Send array in JSON POST request with HTTParty

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: "..."}, ... ] }

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM