I’m working with a REST API, and I need to return a JSON
with my values to it. However, I need the items
of the payload variable to show all the items inside the cart_item
.
I have this:
payload = {
"items": [],
}
I tried this, but I don’t know how I would put this inside the items
of the payload:
for cart_item in cart_items:
item = [
{
"reference_id": f"{cart_item.sku}",
"name": f"{cart_item.product.name}",
"quantity": cart_item.quantity,
"unit_amount": cart_item.product.price
},
]
I need you to get back to me:
payload = {
"items": [
{
"reference_id": "SKU49FS20DD",
"name": "Produto 1",
"quantity": 1,
"unit_amount": 130
},
{
"reference_id": "SKU42920SSD",
"name": "Produto 2",
"quantity": 1,
"unit_amount": 100
}
],
}
response = requests.request(
"POST",
url,
headers=headers,
json=payload
)
I don’t know if I would need to pass what’s in JSON
to the dictionary to change and then send it to JSON
again.
2
Answers
You’re just missing the "append()" method on a list, and the conversion from Python list & dict to a JSON string:
But you don’t need a string to the "json" argument in requests.post, so you can keep your
Instead of trying to create one item at a time, just populate
payload['items']
directly, using a comprehension:Another possible improvement is about
requests
. Instead of usingrequests.requests('POST' ...)
, you can userequests.post(...)
.And finally, if the API really needs
json
to have a validJSON
string, usejson.dumps
to convert it.Putting all together:
Even though I’m almost a hundred percent sure
requests.post()
will do the right thing if you just pass thepayload
as is injson=payload
.