Requests: Error sending payload in python post request

The code behaving strangely that I am unable to understand what’s going on..

The code that works fine:

link = "https://api.luminati.io/dca/trigger_immediate?collector=XXXxxxXXXxxxXXXX" 
head = {"Authorization": "Bearer xxXXxxXXxx" ,"Content-Type": "application/json"}
data = '{"url":"https://www.practo.com/pune/doctor/XXXXXXxXXXXX"}'
res = requests.post(link, headers = head, data = data)
print("Status: "+str(res.status_code), "Message: "+res.text)

Output:

Status: 202 Message: {"response_id":"z7627t1617552745375r14623bt37oo"}

But I want to load "url":"https://www.practo.com/pune/doctor/XXXXXXxXXXXX" this thing dynamically.

url = "https://www.practo.com/pune/doctor/XXXXXXxXXXXX"
link = "https://api.luminati.io/dca/trigger_immediate?collector=XXXxxxXXXxxxXXXX" 
head = {"Authorization": "Bearer xxXXxxXXxx" ,"Content-Type": "application/json"}
data = {"url":url} 
res = requests.post(link, headers = head, data = data)
print("Status: "+str(res.status_code), "Message: "+res.text)

Output:

Status: 500 Message: 'Unexpected token u in JSON at position 7'

Answer

To load data dynamically try using %s string feature, like that:

url = "https://www.practo.com/pune/doctor/XXXXXXxXXXXX"
data = '{"url":"%s"}' % url

or you can convert dictionary entirely to str, like:

import json
data = {"url":link}
res = requests.post(link, headers=head, data=json.dumps(data))

by the way, you can pass body not like data, but like json, here’s documents:

:param json: (optional) json data to send in the body of the :class:Request. So your request will look like:

data = {"url":link}
res = requests.post(link, headers=head, json=data)