Select to view content in your preferred language

Create a Layer object for hosted feature layer

1433
4
Jump to solution
03-10-2022 01:14 PM
MichaelWen_Timmons
Occasional Contributor

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. 

0 Kudos
1 Solution

Accepted Solutions
AlfredBaldenweck
MVP Regular Contributor

Make sure to include the feature class's index number; right now you're pulling the group layer.

 "https://services.arcgis.com..../FeatureServer/0"

View solution in original post

4 Replies
AlfredBaldenweck
MVP Regular Contributor

Sorry, I had an error in my last post and wasn't sure how quickly I could correct it but here we are.

  1. Add data from path, making sure to include the index#
  2. Make layer from a selection by attributes
  3. Remove original layer.

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.

0 Kudos
DonMorrison1
Frequent Contributor

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')

 

0 Kudos
MichaelWen_Timmons
Occasional Contributor

I got an "Input features: Dataset "https://services.arcgis.com..../FeatureServer" does not exist or is not supported" error.

 

0 Kudos
AlfredBaldenweck
MVP Regular Contributor

Make sure to include the feature class's index number; right now you're pulling the group layer.

 "https://services.arcgis.com..../FeatureServer/0"