Skip To Content

Scripting with the ArcGIS REST API

ArcGIS Enterprise can be administered purely through requests to the ArcGIS REST API. Even when you're conducting administrative tasks through your server or portal, calls to the API are being made on the back end. To write scripts that administer ArcGIS Enterprise, you must choose a scripting language that allows you to construct URLs, make HTTP requests, and parse HTTP responses. The examples in this help system use Python.

Using the API does not require Esri software on the machine from which you run the script. All you need is an environment where you can make HTTP requests to your portal.

Get started

To use the ArcGIS REST API, you create an HTTP request for the operation you want to perform and include the required parameters for that operation. You can familiarize yourself with the administrative operations and their required parameters by browsing the series of directories that allow you to interact with the ArcGIS REST APIs. The ArcGIS Enterprise REST APIs are exposed through two portal and two server directories.

Use the ArcGIS REST APIs

The portal and server directories provide interactive views of the ArcGIS REST API resources for your organization. Using these directories can help you understand how to write administrative scripts for your organization.

The URLs to the portal directories are formatted as follows:

The URLs to the server directories are formatted as follows:

To gain familiarity with the ArcGIS REST API, use one of the directories to perform an administrative task. Note the parameters you are required to enter and examine the URL in your browser's address bar as you make the request to the server. Web developer tools such as Fiddler or Firebug can be useful to see the full body of the request and response. This information is valuable when you're attempting to construct your own administrative HTTP requests through Python or another scripting language.

Generate and use a token in scripts

When administering your organization through the portal, server, or their respective directories, you need to provide the username and password of an account with the appropriate privileges. The same concept applies when you write scripts. However, you must understand how authentication occurs when using scripts to administer your organization.

If your organization is configured to use built-in accounts and token authentication, you can use the same administrative accounts and URLs for your scripts that you would use with the portal and server directories. If your organization is configured with organization-specific logins and web-tier authentication, it is recommended that you have your scripts bypass the web adaptor. Use the initial administrator account created after installing Portal for ArcGIS to access the portal or the primary site administrator account created after installing ArcGIS Server to access the server.

In either case, you are returned a token, which is a special string of characters that communicates to the portal or server that you have been authenticated to perform certain types of actions. You must include this token in any web service requests you make.

The following Python function requests a portal token. The portal's URL, username, and password are provided as arguments.

def generateToken(username, password, portalUrl):
    '''Retrieves a token to be used with API requests.'''
    data = urllib.parse.urlencode({'username' : username,
                                   'password' : password,
                                   'client' : 'referer',
                                   'referer': portalUrl,
                                   'expiration': 60,
                                   'f' : 'json'}).encode('utf-8')
    response = urllib.request.urlopen(portalUrl + '/sharing/rest/generateToken',
                                      data).read().decode('utf-8')
    try:
        jsonResponse = json.loads(response)
        if 'token' in jsonResponse:
            return jsonResponse['token']
        elif 'error' in jsonResponse:
            print(jsonResponse['error']['message'])
            for detail in jsonResponse['error']['details']:
                print(detail)
    except ValueError as e:
        print('An unspecified error occurred.')
        print(e)

The following Python function requests a server token. The server's URL, username, and password are provided as arguments.

def generateToken(username, password, serverUrl):
    '''Retrieves a token to be used with API requests.'''
    data = urllib.parse.urlencode({'username' : username,
                                   'password' : password,
                                   'client' : 'referer',
                                   'referer': serverUrl,
                                   'expiration': 60,
                                   'f' : 'json'}).encode('utf-8')
    response = urllib.request.urlopen(serverUrl + '/tokens/generateToken',
                                      data).read().decode('utf-8')
    try:
        jsonResponse = json.loads(response)
        if 'token' in jsonResponse:
            return jsonResponse['token']
        elif 'error' in jsonResponse:
            print(jsonResponse['error']['message'])
            print(jsonResponse['error']['details'])
    except ValueError as e:
        print('An unspecified error occurred.')
        print(e)

The token does not last forever; it is designed to time out so that it cannot be stolen and used indefinitely by a malicious user. Typically, you have to request a new token each time you run your script (but not each time you make a request). In some exceptional cases, tokens can expire before the run of your script ends. If your request includes an expired token, the response from the server will include an error indicating that your token has expired. If this occurs, refresh your token and continue the run of your script.

Work with requests and responses

To make a web service request, you need to formulate the URL for the action you want to take, as well as the required parameters for that action. One of the required parameters is a token such as the one generated above.

All administrative actions produce a web service response, which you'll typically request in JavaScript Object Notation (JSON) format. Scripting languages such as Python have libraries that can parse, or read, a JSON response. Sometimes you just want to get the HTTP status code to find out whether your request succeeded (for example, a code of 200 means OK). Other times, the response may have data, such as log messages, that you want to further parse and examine.