Sub Items and API

Hi there,
I’m working on a python script with the following goal: organization and tracking of property leases, their tenants, and the corresponding rent schedules. The script automates the creation and management of items and subitems in Monday.com, reflecting lease and rent-related information in a structured manner. It provides a way to easily keep track of lease details, tenant information, and rent payment schedules within the Monday.com platform.

I’ve got the main item creation down with the following structure

the script creates items and prevents duplicate items from being created on subsequent run throughs of the script.
The Sub items are also being created however I’m having a difficult time preventing duplicate sub items from being created each time the script is run. Another aspect it updating existing sub items if changes are found
This is the sub item structure

I’ve got variables set up for item column mapping and subitem column mapping which are working

I have a function to check the column values of my sub items which works correctly
def get_subitem_column_values(parent_item_id):
query = f’‘’
{{
items(ids: {parent_item_id}) {{
subitems {{
id
column_values(ids: [“dropdown”, “numbers”, “date0”, “formula”, “text0”, “date6”]) {{
id
title
value
}}
}}
}}
}}
‘’’
I’ve got a function for creating or updating sub items, checking the value in the ChargeID (text0) column for a unique identifier
def create_or_update_subitem(parent_item_id, sub_item_data):
existing_subitem_id = get_subitem_id_by_charge_id(parent_item_id, sub_item_data[‘ChargeID’])

monday_api_url = "https://api.monday.com/v2"
headers = {
    "Authorization": M_API_KEY,
    "Content-Type": "application/json"
}

column_values = ', '.join(
    [f'\\"{SUBITEM_COLUMN_MAPPING[key]}\\": \\"{value}\\"' for key, value in sub_item_data.items() if
     value is not None])

if existing_subitem_id:
    # Update existing subitem columns if needed
    query = f"""
        mutation {{
            change_multiple_column_values(item_id: {existing_subitem_id}, board_id: {BOARD_ID}, column_values: {{ {column_values} }}) {{
                id
            }}
        }}
    """
else:
    # Create new subitem
    query = f"""
        mutation {{
            create_subitem(parent_item_id: {parent_item_id}, item_name: "{sub_item_data['Name']}", column_values: "{{ {column_values} }}") {{
                id
            }}
        }}
    """

data = {"query": query}

response = requests.post(monday_api_url, json=data, headers=headers)

if response.status_code == 200:
    response_json = response.json()
    sub_item_id = response_json.get("data", {}).get("create_subitem", {}).get("id")
    if sub_item_id:
        return sub_item_id
    else:
        print("Failed to get the ID of the created sub-item.")
        print("Response content:")
        print(response.content)
        return None
else:
    print(f"Failed to create or update sub-item. Status code: {response.status_code}")
    print("Response content:")
    print(response.content)
    return None

Everything has come together pretty easily except for this last part that will prevent duplicate sub items from being created and updating existing sub items if anything needs to be updated

Any help or a point in the right direction would be extremely appreciated.
Thank you

Hello there @Casecrs,

I do not have experience with Python, but which step of the process for preventing duplicates for subitems is failing? Are you not getting the data from the subitems? Are you getting the data but there is an error in it? Which piece of information are you trying to get and not getting?

Looking forward to hearing from you :slightly_smiling_face:

Cheers,
Matias

It appears that the step responsible for comparing the data and identifying existing subitems using their shared identifier (ChargeID) might be encountering some issues. This could potentially arise from inconsistencies between the two datasets or a potential error in the comparison logic itself.

This is a sample of what’s being pulled from an existing sub item in the Board. attempting to use the ChargeID as the check to both prevent duplicates .

{‘data’: {‘items’: [{‘subitems’: [{‘id’: ‘5007886819’, ‘column_values’: [{‘id’: ‘dropdown’, ‘title’: ‘Rent Status’, ‘value’: ‘{“ids”:[3],“override_all_ids”:true}’}, {‘id’: ‘numbers’, ‘title’: ‘Rent Amount’, ‘value’: ‘“100000.0”’}, {‘id’: ‘date0’, ‘title’: ‘End Date’, ‘value’: None}, {‘id’: ‘formula’, ‘title’: ‘Projected Rent Increase @ 2.5%’, ‘value’: None}, {‘id’: ‘text0’, ‘title’: ‘ChargeID’, ‘value’: ‘“2962”’}, {‘id’: ‘date6’, ‘title’: ‘StartDate’, ‘value’: ‘{“date”:“2023-09-01”,“time”:null}’}]}

as far as I can tell I’m getting every piece of data I need, the correct data is being used when creating sub items, existing sub item data is being pulled, containing all the info required. I’m now leaning more toward a logic issue rather than being unable to get information from Monday.

Hello again @Casecrs,

If all the needed information is retrieved correctly, then it looks like the issue might lie in the script as you mention.

If you can’t find the source of the issue, you can send us an email to appsupport@monday.com and we will do our best to help you with it :grin:

Cheers,
Matias

Thanks Matias,
I’ve reached out via email.

Fantastic @Casecrs,

Our team will take a look into this :grin:

Looks like I’ve made some progress and have a working way to prevent duplicate sub items from being created.
Now the issue lies in updating existing sub items and I’m getting a parse error from my query

Mutation Query:
mutation {
change_multiple_column_values(item_id: *********, board_id: **********, column_values: {“date0”: null}) {
id
}
}

Response: {‘errors’: [{‘message’: ‘Parse error on “date0” (STRING) at [3, 106]’, ‘locations’: [{‘line’: 3, ‘column’: 106}]}], ‘account_id’: ********}

I’m hesitant to blame the query as I know items are created correctly and the End Date column is populated with the correct date for newly created items but when trying to update sub items we run into this issue.

Hello again @Casecrs,

Can you please try a mutation like this one:

mutation {
  change_multiple_column_values(
    item_id: 11111111
    board_id: 2222222
    column_values: "{\"date0\" : null}"
  ) {
    id
  }
}

Let me know how that goes!

Cheers,
Matias

Hi,
I tried using this format and it wasn’t successful but from there I believe I’ve moved a step closer to getting this.

I’ve formatted a query and am getting this response
mutation {
change_column_value(
item_id: 5023970068,
board_id: 4867329591,
column_id: “date0”,
value: “2023-08-20”
) {
id
}
}

Mutation Response:
{‘error_message’: “809: unexpected token at ‘-08-20’”, ‘status_code’: 500}

I think if I can figure out why it’s not responding with the full end date and correct that issue I should be good to go

Hi @Casecrs,

The change_column_value mutation requires JSON in the value argument. You can replace your IDs in the mutation below and give it a try!

mutation {
  change_column_value(item_id: 9876543210,board_id: 1234567890,column_id: "date0",value: "{\"date\" : \"2023-08-20\"}") {
    id
  } 
}

Alternatively, you can use a string to update the date with the change_simple_column_value mutation for the date column (see here)

Hope this helps! :slight_smile:

Thanks Rachel,
I actually just got it working by changing my query from the last post to change_simple_column_value. It is now updating the end date as expected.

Great to hear! Let us know if you have any other questions.

I now have a script that successfully does the following,
pulls required information from Buildium
formats the information from Buildium into Items and Sub items in Monday
doesn’t create duplicates when run more than once and if changes are found between Buildium information and Monday information it updates the Monday information with the new info pulled from Buildium.

Thanks so much for the help Matias and Rachel.

1 Like