Sending nested json data with Python requests and in x-www-form-urlencoded
<p>I cannot figure out how to do this. Basically one particular API is asking for </p>

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

<p>yet they want the form data to be like this:</p>

<pre><code>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
  }
]
</code></pre>

<p>What I'm doing is this:</p>

<pre><code>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&amp;stockLevels=LocationId&amp;stockLevels=Level
    # this is not correct, it should be something like:
    # stockLevels:[{"SKU":"P01", "LocationId":"00000000", "Level":4}]

    print r
    # &lt;Response [400]&gt; (obivously)
</code></pre>

<p>Any ides on what do I do wrong?</p>

<p>After mining this <a href="https://github.com/LinnSystems/LinnworksNetSDK" rel="nofollow">GitHub repo's examples</a>, their approach seems to be the following:</p>

<ol>
<li>The body is, indeed, <code>x-www-form-urlencoded</code></li>
<li>Complex parameters are JSON strings encoded for <code>x-www-form-urlencoded</code></li>
</ol>

<p>So looking at <a href="https://github.com/LinnSystems/LinnworksNetSDK/blob/master/Linnworks/src/php/Stock.php#L63" rel="nofollow">their PHP example</a> for the <a href="https://apps.linnworks.net/Api/Method/Stock-CreateVariationGroup" rel="nofollow">CreateVariationGroup</a> call, try this:</p>

<pre><code>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
</code></pre>

python json python-requests