Search code examples
pythonxmlhttprequestpostman

request payload from Postman works but mine doesn't - unexpected token error


I took the Python-Requests code from my postman POST request that looks like the following:

payload="{\"action\":\"ask\",
\"PortfolioItem\":{\"localAmount\":0,\"expiresAt\":\"2021-04-25T18:50:09+0000\",\"skuUuid\":\"9c0b30f6-d2e0-49ff-b8fa-c30a4d8d9b82\",\"localCurrency\":\"USD\",\"meta\":{\"discountCode\":\"\"}}}"

headers = {//bunch of headers}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

This works fine. But when I try passing new information into the payload, using the following code:

//initialize an empty payload object
payload = {
 'action': 'ask','PortfolioItem': {'expiresAt': '',
  'localAmount': 0,
  'localCurrency': 'USD',
  'meta': {'discountCode': ''},
  'skuUuid': ''
}}

//populate it with data I want to add
payload['PortfolioItem']['expiresAt'] = expiration
payload['PortfolioItem']['localAmount'] = price
payload['PortfolioItem']['skuUuid'] = sku_id

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

I get the following error: {"message":"Unexpected token P in JSON at position 0"}. I tried turning my payload into a string as well, ie: data=str(payload), but that returns the same error {"message":"Unexpected token ' in JSON at position 0"}. On top of that, I tried just splitting up the original payload and concatenating it with the new data in between, but I need to pass integer values so concatenating doesn't work (unless there's a way I can do that without it converting my int into a string). Not sure what is wrong, any help would be appreciated!


Solution

  • The first is a string that looks like valid JSON, the second is a dict. You need to transform your dict into JSON. Or use: requests.request("POST", url, headers=headers, json=payload) to have it done for you.