Building Queries with REST Endpoints

If you've taken the time to learn a little bit about a layer or table in a REST endpoint, the query forms you'll find in one of Esri's are invaluable. Let's say you want to see what an example record looks like. Well, just figure out how to find OBJECTID 1, or 1000. Or if you know one column is "Name", figure out how to query for "Smith". You'll know you're successful if you get results at the bottom of the form. And once you have that, you have a URL that you can copy and paste into your Javascript code in order to build a dynamic query for your users. All you have to do is switch the format from "html" to "json" and you've got something your web app can consume, parse with code, and display to your users.

Let's take a look at the query form available for the Detailed Counties Layer we looked at in the Explore with a Browser section. Once again for your testing excitement, here it is in an iframe:

When you're working with this form, keep in mind that the "Query (Get)" button is near the bottom, and if you hit "Enter" you might fire it off. Also, there are sometimes elements that, if skipped, can hose up the query. But usually it only takes a few tries to get a good query working. Especially if the endpoint is set up well. This one is relatively easy to use just with the "Name" field at the top. Type in "Dade" and hit your Enter key. Here are links to the results (with the HTML version, they appear below the query form):

You can see you don't need the exact spelling to get results in this example - you get two "Dade" counties as well as "Miami-Dade". But with the defaults, we get a heck of a lot more geometry than we get other text. This is great if we're making a map, but not the best if we're interested in attributes. (You could argue that we should use Coarse Counties if we're not interested in mapping!) In order to get something a bit more human-readable, let's make two changes:

  1. Flip the "Return Geometry" radio button to "False."
  2. Place a "*" in the "Return Fields" input.

Hit "Enter" and you'll see the results are a bit easier to read and understand. These three counties are in Florida, Georgia, and Missouri, along with dozens of demographic results. You can switch the "Format" button at the bottom to "JSON" to change your format. This will actually switch the format in the URL to "pjson" so you can see the "pretty" or "padded" version. But if you're writing code you can set the "f" (format) parameter to just "json" and get the minified version. Here's a link for you to see that.

The button below grabs a random letter of the alphabet and queries the layer. Crack open your developer console and watch the Net tab to see how the query gets fired and produces the results shown below. Check out the getRandomCounty function in the source code in GitHub to see more details about how this is done.

  • Query URL:
  • Number of Counties Returned:
  • First County Returned:
  • 2007 Population: