ArcPy – Using ArcPy with Hosted Feature Service Layers from ArcGIS Online

arcgis-onlinearcgis-python-apiarcpycalculate-geometryfeature-service

Is it possible to use the arcpy library with hosted feature service layers from ArcGIS Online?

I am aware of the ArcGIS API for Python, but the API lacks many of arcpy's features.

In my case, I'd like to script populating a new field of a point layer with the layer's XY attributes (latitude and longitude). This is known as 'Calculate Geometry' in ArcMap and 'Add Geometry Attributes' in ArcGIS Pro.

I need this to be scripted, rather than done manually, because I am working with a layer that frequently has additional points added to it via Survey123. Survey123 does not automatically record the longitude and latitude of points added to it through its form, and again, the ArcGIS API for Python does not cover 'Calculate Geometry' to my knowledge. Finally, I would prefer not to download the ArcGIS Online layer, run arcpy scripts on it locally, then re-publish the layer, since this tends to reset symbology, field names, etc. – but if anyone who knows more about ArcGIS Online can help with this strategy, that could solve the problem as well.

The arcpy code would be something as simple as:

import arcpy
arcpy.env.workspace = <some file gdb>
arcpy.AddGeometryAttributes_management(<name of the layer as a string>, "POINT_X_Y_Z_M")

But in my case, instead of a feature class in file geodatabase stored locally, all I have is a hosted feature service. I've tried using the REST endpoint url as the workspace, but it doesn't seem to work. I've also tried extracting the feature layer itself via the ArcGIS API for Python, then using that in the arcpy code:

search_result = gis.content.search(query="<my layer name>", max_items=1, item_type="Feature Service")
# or search_result = gis.content.get(<item ID of my layer>)
item = search_result[0]
item_layers = item.layers
layer_fset = item_layers[0].query()
layer_features = layer_fset.features
layer_flayer = item_layers[0]

But that doesn't seem to work, either.
Either I'm missing something or perhaps it's not possible.

Best Answer

Using ArcGIS Pro 2.5 and making sure my feature service was editable with update privileges I was able to get the following line of code to work: arcpy.management.AddGeometryAttributes("https://services.arcgis.com/<myCode>/arcgis/rest/services/<MyLayer>/FeatureServer/0", "POINT_X_Y_Z_M", None, None, None)

Related Question