emihir0 emihir0 - 3 months ago 29
JSON Question

Sending nested json data with Python requests and in x-www-form-urlencoded

I cannot figure out how to do this. Basically one particular API is asking for

'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'


yet they want the form data to be like this:

stockLevels=[
{
"SKU": "sample string 1",
"LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
"Level": 3
},
{
"SKU": "sample string 1",
"LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
"Level": 3
}
]


What I'm doing is this:

def change_stock_quantity(self, SKU, qty):
# Note that this will change quantity of just one item
# instead of two like in the example above
payload = {
'stockLevels':[{
'SKU': SKU,
'LocationId': self.ebay1_location_id,
'Level': qty,
}]
}
r = self.session.post(self.session_server + '//api/Stock/SetStockLevel',
data=payload)

print r.request.body
# stockLevels=SKU&stockLevels=LocationId&stockLevels=Level
# this is not correct, it should be something like:
# stockLevels:[{"SKU":"P01", "LocationId":"00000000", "Level":4}]

print r
# <Response [400]> (obivously)


Any ides on what do I do wrong?

Answer

After mining this GitHub repo's examples, their approach seems to be the following:

  1. The body is, indeed, x-www-form-urlencoded
  2. Complex parameters are JSON strings encoded for x-www-form-urlencoded

So looking at their PHP example for the CreateVariationGroup call, try this:

stockLevels=[
  {
    "SKU": "sample string 1",
    "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
    "Level": 3
  },
  {
    "SKU": "sample string 1",
    "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
    "Level": 3
  }
]

payload = {'stockLevels' : json.dumps(stockLevels)}

# send payload encoded with x-www-form-urlencoded