'Pass variable in Json payload?
I have the following code:
import requests
import time
orderID = time.strftime("%#d%m%y") + str(randint(10, 99))
payload = '{ "id": 62345, "shippingCharge": 0.0, "giftCharge": 0.0, "amountDue": 13000.0}'
url = "test.com/v1/%s".format(orderID)
s = requests.Session()
s.headers.update({'Content-Type': 'application/json'})
r = s.post(url , payload, auth=('test01', 'test01'))
I want to pass the variable orderID in the following:
- as the value for
idfield in the JSON payload. - After
v1in the URL string
Please help me out.
Solution 1:[1]
I think this will work:
import requests
from random import randint
import time
orderID = time.strftime("%#d%m%y") + str(randint(10, 99))
payload = ('{ "id": ' + str(orderID) + ', "shippingCharge": 0.0, "giftCharge": 0.0, '
'"amountDue": 13000.0}')
url = "test.com/v1/{}".format(orderID)
s = requests.Session()
s.headers.update({'Content-Type': 'application/json'})
r = s.post(url , payload, auth=('test01', 'test01'))
Solution 2:[2]
1) as the value for id field in the JSON payload.
orderID = time.strftime("%#d%m%y") + str(randint(10, 99))
payload = '{ "id": '+ str(orderID) +', "shippingCharge": 0.0, "giftCharge": 0.0,
"amountDue": 13000.0}'
2) After v1 in the URL string
The code you have given is correct for your use case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | martineau |
| Solution 2 |
