API POST with array using HTTP gem (or RestClient)

▼魔方 西西 提交于 2019-12-02 07:51:42
def self.submitorder 
  itemsarray = { :items => [ { :product_id => 423, :brand_id => 33, :color_id => 498, :size_id => 4, :quantity => 1, :front_print => 1389517,
        :front_mockup => 1390617 } ] }
  req = HTTP.post("https://api.printaura.com/api.php", :json => { 
    :key => APIKEY, 
    :hash => APIHASH, 
    :method => "addorder",
    :businessname => "this is a secret too",
    :businesscontact => "thats a secret",
    :email => "my@email.com",
    :your_order_id => "1",
    :returnlabel => "FakeAddress",
    :clientname => "ShippingName",
    :address1 => "ShippingAddressLine1",
    :address2 => "ShippingAddressLine2",
    :city => "ShippingCity",
    :state => "ShippingState",
    :zip => "ShippingZip",
    :country => "US",
    :customerphone => "dontcallme",
    :shipping_id => "1",
    :items =>  Base64.encode64(itemsarray.to_json)}
)

  puts JSON.parse(req)

I really hopes this helps somebody some years from now haha

To create a array in JSON you use an array in Ruby. Its that easy.

require 'json'

def self.submitorder   
  req = HTTP.post("https://api.printaura.com/api.php", :json => { 
        :key => APIKEY, 
        :hash => APIHASH, 
        :method => "addorder",
        :businessname => "this is a secret too",
        :businesscontact => "thats a secret",
        :email => "my@email.com",
        :your_order_id => "1",
        :returnlabel => "FakeAddress",
        :clientname => "ShippingName",
        :address1 => "ShippingAddressLine1",
        :address2 => "ShippingAddressLine2",
        :city => "ShippingCity",
        :state => "ShippingState",
        :zip => "ShippingZip",
        :country => "US",
        :customerphone => "dontcallme",
        :shipping_id => "1",
        :items => [ 
           {
             :product_id => 423,
             :brand_id => 33,
             :color_id => 498,
             :size_id => 4,
             :front_print => 1389517,
             :front_mockup => 1390615,
             :quantity => 1
           }
        ]
    })

  puts JSON.parse(req)

The API lists a items parameter which should contain an array of objects. It says nothing about itemsarray.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!