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.
CodePudding user response:
Instead of trying to create one item at a time, just populate payload['items']
directly, using a comprehension:
payload['items'] = [
{
'reference_id': cart_item.sku,
'name': cart_item.product.name,
'quantity': cart_item.quantity,
'unit_amount': cart_item.product.price
}
for cart_item in cart_items
]
Another possible improvement is about requests
. Instead of using requests.requests('POST' ...)
, you can use requests.post(...)
.
And finally, if the API really needs json
to have a valid JSON
string, use json.dumps
to convert it.
Putting all together:
import requests
import json
payload['items'] = [
{
'reference_id': cart_item.sku,
'name': cart_item.product.name,
'quantity': cart_item.quantity,
'unit_amount': cart_item.product.price
}
for cart_item in cart_items
]
response = requests.post(
url,
headers=headers,
json=json.dumps(payload)
)
Even though I'm almost a hundred percent sure requests.post()
will do the right thing if you just pass the payload
as is in json=payload
.
CodePudding user response:
You're just missing the "append()" method on a list, and the conversion from Python list & dict to a JSON string:
from json import dumps
items_dict = []
for cart_item in cart_items:
items_dict.append({
"reference_id": f"{cart_item.sku}",
"name": f"{cart_item.product.name}",
"quantity": cart_item.quantity,
"unit_amount": cart_item.product.price
})
payload = {
'items': items_dict
}
# And if you want a JSON string as output
print(dumps(payload))
But you don't need a string to the "json" argument in requests.post, so you can keep your
response = requests.request(
"POST",
url,
headers=headers,
json=payload
)