Create an Item using Python dictionary

I want to create an item using Python, I have the following dictionary:
item_data = {
“account_contact”: “account_contact”,
“people”: “people”,
“status0”: ‘{status0: “status0”}’,
“numbers”: 987,
“numbers8”: 45847,
“date”: ‘{“date”:“2023-07-01”}’,
“formula”: None,
“numbers7”: “7”,
“formula3”: None,
“status8”: “status8”,
“date3”: ‘{“date”:“2023-07-01”}’}

I want to execute the following:
query = ‘’‘mutation {
create_item(board_id: 0000000000000, item_name: “new item from Python abc”, column_values: ‘’’ + json.dumps(item_data).replace(‘"’, ‘"’) + ‘’‘) {
id
}
}’‘’

print(query)

mutation {

create_item(board_id: 5203759868, item_name: "new item from Python abc", column_values: {"account_contact": "account_contact", "people": "people", "status0": "{status0: \"status0\"}", "numbers": 987, "numbers8": 45847, "date": "{\"date\":\"2023-07-01\"}", "formula": null, "numbers7": "7", "formula3": null, "status8": "status8", "date3": "{\"date\":\"2023-07-01\"}"}) {
    id
}

}

query_to_run = {‘query’: query}

r = requests.post(url=apiUrl, json=query_to_run, headers=MONDAY_HEADERS)

I am getting the following error:
[{‘message’: ‘Parse error on “account_contact” (STRING) at [2, 94]’, ‘locations’: [{‘line’: 2, ‘column’: 94}]}]

Hey! The column values needs to be a JSON string, which is why you’re getting an error.

Instead of doing string concatenation, I’d use GraphQL variables here - it’s less error-prone and handles JSON strings a bit more elegantly: https://graphql.org/learn/queries/#variables

The way to use it is the following:

Step 1 - replace the column values JSON with a variable in your mutation:

mutation ($colVals:JSON!) {
  create_item(board_id: 000000000000, item_name: “new item from Python abc”, column_values: $colVals) {
    id
  }
}

step 2 - pass the dictionary (as a string) as a variable in the final http request -

{
  "query" : "mutation($colVals:JSON!) { ... }",
  "variables" : {
    "colVals": "{ \"account_contact\" : \"account_contact\", ... }"
}
1 Like