I have a list of items that I want to add to the payload for a bulk API requests. I don't seem to be able to add the items to the payload JSON the right way.
This is what I want to do:
import json
fruits = ['apple','pear','banana']
headers = {
'X-Api-Key': API_KEY,
'Content-Type': 'application/json',
}
data = {
"requests": [
{
"params": {
"fruit": ["apple"]
}
},
{
"params": {
"fruit": ["pear"]
}
}
{
"params": {
"fruit": ["banana"]
}
}
]
}
json_responses = requests.post(
'https://foo.bar/api/bulk',
headers=headers,
json=data
).json()
How do I add a new params
item to the data payload for each item in my list?
I found this answer from a few years ago but if I try:
my_fruits = json.dumps([dict(fruit=f) for f in fruits])
And then insert it like this I get the error "Object of type set is not JSON serializable".
I'm sure it's because I'm doing something wrong when converting my list to a dictionary and then adding it wrongly but I'm a bit stuck.
EDIT: To clarify, the issue I'm stuck with is how to iterate through the list of fruits and automatically add a param
for them in the data
dictionary before the request is made.