macxred / cashctrl_api

Python client for the CashCtrl REST API
MIT License
0 stars 0 forks source link

How to handle (non-supported) dict values #4

Closed chappi closed 4 months ago

chappi commented 4 months ago

The following code demonstrates how to use dict fields with the cashcctrl_api. I.e. the dict must be converted to a json string with e.g. json.dumps. Based on a cc discussion. Code taken from the README in the 'hps/json-strings' branch.

import json
from cashctrl_api import CashCtrlAPIClient

cc = CashCtrlAPIClient()

# create contact
contact = {
    "firstName": "Tobias",
    "lastName": "Treichler",
    "addresses": json.dumps(
        {"type": "MAIN",
         "address": "Teststreet 15",
         "zip": "1234",
         "city": "Testtown"
        }),
    "titleId": 2
}
response = cc.post("person/create.json", data=contact)
id = response["insertId"]

# delete the contact again
response = cc.post("person/delete.json", params={'ids': id})
print(response)

Not sure if we want to expose the json.dumps complication or if it should be handled internally?

lasuk commented 4 months ago

Here's a generic solution:

import json
from cashctrl_api import CashCtrlAPIClient

cc = CashCtrlAPIClient()

contact = {
    "firstName": "Tobias",
    "lastName": "Treichler",
    "addresses": 
        [{"type": "MAIN",
         "address": "Teststreet 15",
         "zip": "1234",
         "city": "Testtown"
        }],
    "titleId": 2
}

# THIS DOES NOT WORK (AS REPORTED)
response = cc.post("person/create.json", data=contact)
print(response)
## {'success': False, 'message': None, 'errors': [{'field': 'addresses', 'message': 'The JSON is invalid.'}]}

def flatten_dict(d):
    return {k: (json.dumps(v) if isinstance(v, (list, dict)) else v) for k, v in d.items()}

# THIS WORKS
response = cc.post("person/create.json", data=flatten_dict(contact))
print(response)
## {'success': True, 'message': 'Person saved', 'insertId': 22}

# delete the contact again
response = cc.post("person/delete.json", params={'ids': id})
print(response)
lasuk commented 4 months ago

I propose to adapt CashCtrlAPIClient._request() such that it always invokes flatten_dict on data.