I'm trying to write a Python script that queries a hosted feature layer in AGOL, and then use returned records as the input for some arcpy geoprocessing commands to update a mosaic dataset. I am able to do the query in Pro if I manually the hosted feature layer to a map, and then just use the layer name as the input for arcpy.management.SelectLayerByAttribute.
However I'm having trouble figuring out how to create a "layer" object in Arcpy from a hosted feature layer. "Make Feature Layer" seems to work only for feature classes.
I'd prefer not to run the script as a Notebook using ArcGIS Python API as there are some local file system tasks that I want to handle.
Solved! Go to Solution.
Make sure to include the feature class's index number; right now you're pulling the group layer.
Sorry, I had an error in my last post and wasn't sure how quickly I could correct it but here we are.
Not as clean as I imagine either of us would like, but it does work.
p = arcpy.mp.ArcGISProject("CURRENT")
mapA = p.activeMap
hostedFC = 'https://services1.arcgis.com/.../0' # The layer you're querying
# Make sure to include the index number or else it'll grab you the group layer, and that won't work.
hostLay= mapA.addDataFromPath(hostedFC) # Add data
lyrAlias = hostLay.name + "_Selection" # Name the selection layer.
arcpy.management.MakeFeatureLayer(hostLay, lyrAlias, "FID = 299")
mapA.removeLayer(hostLay)
Hope this helps!
Edit: Don's answer is far more elegant.
You can create a layer from an AGOL hosted feature layer by referencing the hosted feature layer's URL. For example:
url = 'https://services2.arcgis.com/dJOijx2lWTlGQBDJ/arcgis/rest/services/CW_3863/FeatureServer/0'
arcpy.management.MakeFeatureLayer(url, 'NewLayer')
I got an "Input features: Dataset "https://services.arcgis.com..../FeatureServer" does not exist or is not supported" error.
Make sure to include the feature class's index number; right now you're pulling the group layer.