I am retrieving a list of objects from an external API that I need to send as the payload to a webhook using post request in python.
The structure of the data returned from get_data()
looks like this
[{"eventId": 1,
"eventType": "test",
"properties": {
"property1": "value1",
"property2": "value2",
"property3": "value3",
}},
{"eventId": 2,
"eventType": "test",
"properties": {
"property1": "value1",
"property2": "value2",
"property3": "value3",
}},
{"eventId": 3,
"eventType": "test",
"properties": {
"property1": "value1",
"property2": "value2",
"property3": "value3",
}}]
headers = {"Content-Type": "application/json",}
payload = get_data()
response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
it raises a TypeError('Object of type ExternalUnifiedEvent is not JSON serializable)
; if i remove the json.dumps()
and just pass in the payload as the data, I'm getting TypeError('cannot unpack non-iterable ExternalUnifiedEvent object')
def get_data():
try:
api_response = client_api.get()
data = []
for i in api_reponse:
e = {
"event_id": i.event_id
"event_type": i.event_type
"properties": i.properties
}
data.append(e)
return data
except Exception as e:
print(e)
CodePudding user response:
Your get_data
function is returning an ExternalUnifiedEvent
object instead of a list or another JSON serializable object.
You should fix your get_data
function or provide a custom JSONDecoder
to the dumps
method as a cls
paramater:
json.dumps(payload, cls=YourCustomJSONEncoder)
You can see how to make your custom JSON encoder class in the json python lib docs.