Michal Grzelak
Michal Grzelak

Reputation: 321

python3 request body with variable

I stuck in my Python3 code when using requests to make HTTP POST requests. I need to put variable "PackageId" inside data and gets error:

{"meta":{"code":4015,"type":"Bad Request","message":"The value of `carrier_code` is invalid."},"data":[]}

My code is:

import requests
import json

PackageId = input("Package number:")

headers = {
   'Content-Type': 'application/json',
   'Trackingmore-Api-Key': 'MY-API-KEY',
}

data = { 
   'tracking_number': PackageId,
   'carrier_code': 'dpd-poland'
}
request = requests.post('https://api.trackingmore.com/v2/trackings/post', headers=headers, data=data)

The HTTP POST method used is fine, becouse when I hardcode the PackageId in Body, request is successful.

data = '{ "tracking_number": "1234567890", "carrier_code": "dpd-poland" }'

What might be wrong? Please help, I stuck and spend many hours trying to find a problem.

Here is a CURL command I want to reproduce:

curl -XPOST -H 'Content-Type: application/json' -H 'Trackingmore-Api-Key: MY-API-KEY' -d '{ "tracking_number": "01234567890", "carrier_code": "dpd-polska"  }' 'https://api.trackingmore.com/v2/trackings/post'

Thanks !!!

Upvotes: 1

Views: 3120

Answers (1)

cody
cody

Reputation: 11157

You need to convert the data dict to a json string when providing it to post(), it does not happen implicitly:

request = requests.post('https://api.trackingmore.com/v2/trackings/post', headers=headers, data=json.dumps(data))

Upvotes: 1

Related Questions