Querying a map service with the ArcGIS REST API and Python

The query operation in the ArcGIS REST API performs a query against a map service and returns a feature set. The feature set includes values for fields requested by the user and can also return geometry, if requested.

Getting ready

In this recipe, you will build on the first recipe, in which you generated a URL using the ArcGIS Services page dialog box to generate results. In this recipe, you will use the ArcGIS Server Services page dialog box to generate a URL request that queried a map service layer and returned results. You may recall that the URL was http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/1/query?text=&geometry=&geometryType=esriGeometryPolygon&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&objectIds=&where=STATE_FIPS+%3D+%2748%27+and+CNTY_FIPS+%3D+%27021%27&time=&returnCountOnly=false&returnIdsOnly=false&returnGeometry=false&maxAllowableOffset=&outSR=&outFields=POP2000%2CPOP2007%2CBLKGRP&f=pjson.

Now, let's learn how to submit this request using Python.

How to do it…

  1. In IDLE or another Python development environment, create a new Python script called QueryMapService.py and save it to the C:ArcpyBookCh12 folder.
  2. In your browser, navigate to: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r3000000p1000000. This is the REST API page for the query operation against a layer in a map service. As you scroll down the help page, you should see the same parameters as were generated using the dialog box, such as geometry, geometryType, inSR, spatialRel, where, and others.
  3. In your script, import the requests and json modules:
    import requests
    import json
  4. Create the following agisurl variable. This will serve as the base URL that references the query operation on the census block group layer (identified by an identifier of 1 in the URL) in the ESRI_Census_USA map service:
    import requests
    import json
    agisurl = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/1/query"
    
  5. Now, create a Python dictionary object, as shown in the following code. We're going to leave out some of the parameters that were not defined or used in the dialog box. We're just creating an attribute query in this instance so that all the geometry parameters can be removed:
    import requests
    import json
    agisurl = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/1/query"
    payload = { 'where':'STATE_FIPS = '48' and CNTY_FIPS =       '021'','returnCountOnly':'false',
    'returnIdsOnly': 'false', 'returnGeometry':'false', 
    'outFields':'POP2000,POP2007,BLKGRP',
    'f': 'pjson'}
    
  6. The requests.get() method can accept a Python dictionary object as the second parameter. This dictionary defines the set of key/value pairs that help define the query string. Add the requests.get() method:
    import requests
    import json
    agisurl = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/1/query"
    payload = { 'where':'STATE_FIPS = '48' and CNTY_FIPS =       '021'','returnCountOnly':'false', 
    'returnIdsOnly': 'false', 'returnGeometry':'false', 
    'outFields':'POP2000,POP2007,BLKGRP', 
    'f': 'pjson'}
    r = requests.get(agisurl, params=payload)
    
  7. Include a print statement in order to print the response that is returned.
    import requests, json
    agisurl = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/1/query"
    payload = { 'where':'STATE_FIPS = '48' and CNTY_FIPS =       '021'','returnCountOnly':'false', 
    'returnIdsOnly': 'false', 'returnGeometry':'false', 
    'outFields':'POP2000,POP2007,BLKGRP', 
    'f': 'pjson'}
    r = requests.get(agisurl, params=payload)
    print(r.text)
    
  8. Save the script and run it to see this output:
    How to do it…
  9. Now, convert this JSON object to a Python dictionary. Also, comment out the print statement that you added in the last step:
    r = requests.get(agisurl, params=payload)
    #print(r.text)
    decoded = json.loads(r.text)
  10. The Python dictionary object returned by the json.loads() method will contain the contents of the JSON object. You can then pull the individual data elements out of the dictionary. In this case, we want to pull out the attributes of each of the feature returned (BLKGRP, POP2007, and POP2000). We can do so by using the following code, which you'll need to add to your script:
    r = requests.get(agisurl, params=payload)
    #print(r.text)
    decoded = json.loads(r.text)
    for rslt in decoded['features']:
        print("Block Group: " + str(rslt['attributes']['BLKGRP']))
        print("Population 2000: " + str(rslt['attributes']['POP2000']))
        print("Population 2007: " + str(rslt['attributes']['POP2007']))
    
  11. You can check your work by examining the C:ArcpyBookcodeCh12QueryMapService.py solution file.
  12. Save and execute your script to see these results:
    How to do it…

How it works…

The query operation in the ArcGIS REST API can be used to perform spatial and attribute queries against a layer in an ArcGIS Server map service. We used the requests.get() method to perform an attribute query against the census block groups layer. We included various parameters, including a where clause that will only return records where the ST_FIPS code is 48 and the CNTY_FIPS code is 021 (Bexar County, Texas). The response object was then converted to a Python dictionary and we included a for loop to iterate through each of the returned records and print out the block group name, and the population for the years 2000 and 2007.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset