I'm attempting to add new fields to a hosted feature layer if they don't already exist. Currently my code will add the first field in the list (dictionary), but then fails with the message:
Exception: Unable to add feature service layer definition.
Invalid definition for System.Collections.Generic.List`1[ESRI.ArcGIS.SDS.FieldInfo]
Object reference not set to an instance of an object.
(Error Code: 400)
If it's run a second time it does not add the second field and gives the same error. I added the sleep thinking it may help but it doesn't. Any suggestions appreciated. Thanks.
from arcgis.gis import GIS
from arcgis.features import FeatureLayer
import time
username = ''
password = ''
gis = GIS("<url>", username, password, verify_cert=False)
item_id = "<item_id>"
feature_layer_item = gis.content.get(item_id)
feature_layer = FeatureLayer.fromitem(feature_layer_item)
#feature_layer = FeatureLayer.fromitem(feature_url)
fields = feature_layer.properties.fields
existing_field_names = [field.name for field in fields]
new_fields = [
{"name":"newfield1", "alias": "New Field 1","type": "esriFieldTypeInteger"},
{"name":"newfield2", "alias": "New Field 2","type":"esriFieldtypeInteger"},
{"name":"newfield3", "alias": "New Field 3","type":"esriFieldtypeInteger"}
]
fields_to_add_list = [] # this is named 'list' but is actually a dictionary
for new_field in new_fields:
if new_field["name"] not in existing_field_names:
fields_to_add_list.append(new_field)
print(f"Field '{new_field['name']}' will be added.")
else:
print(f"Field '{new_field['name']}' already exists.")
for field_to_add in fields_to_add_list:
print(field_to_add)
feature_layer.manager.add_to_definition({"fields":[field_to_add]})
time.sleep(20)