About this demo
You will build two scripts with the ArcGIS API for Python:
create_api_key.pycreates the API key credentials and generates the first key, in slot 1.rotate_api_key.pyrotates that key without downtime, using the second slot.
Each Item method they call wraps one REST request; the REST API tutorial shows them one by one.
Check prerequisites
An ArcGIS Location Platform, ArcGIS Online, or ArcGIS Enterprise 11.5+ account with a Creator user type or higher and the Generate API keys and Assign privileges to OAuth 2.0 applications privileges. Ideally a service user with only those.
Python 3.10+, arcgis 2.4.2+ and python-dotenv.
The Result pane shows output captured earlier, with made-up ids and keys. Nothing on this page sends a request.
Install the package
Install arcgis and python-dotenv in a virtual environment, so they don’t clash with other versions on your machine:
python3.11 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python -c "import arcgis; print(arcgis.__version__)"Version requirements
The developer credentials methods need arcgis 2.4.2 or later, which needs Python 3.10 or later (3.11 or later for arcgis 2.4.3).
Configure the scripts
Copy .env.example to .env and fill it in. .gitignore keeps it out of your repository.
GIS takes the portal’s https://www.arcgis.com for ArcGIS Online and ArcGIS Location Platform, https://<host>/<web-adaptor> for ArcGIS Enterprise. Not the /sharing/rest URL the REST API uses.:
The scripts sign in with Backend jobs can’t sign in as you: a username and password don’t work with SAML/SSO or MFA. Create the app credentials in the portal as a service user and assign them that user’s privileges. They are not the client ID and secret of the API key item the script creates., not as you:
Keep the
client_secretin a secret manager, and create the app credentials as a service user with only the privileges these scripts need. With admin privileges, the secret can do almost as much damage as your password.
Why the app credentials need their owner’s privileges
Creating and rotating keys with app credentials needs their owner’s user privileges. The secret can’t sign in or change your password, but it can do whatever those privileges allow.
In production, the same variables can come from the environment or a secret manager instead of .env.
Import the modules
GIS: signs in and reaches the portal’s content.ItemPropertiesandItemTypeEnum: describe the credential item.load_dotenv: loads.envintoos.environ.
Sign in
With client_id and client_secret, GIS gets an app token and reuses it for every call that follows.
Other ways to sign in
| Method | Use it for | Limits |
|---|---|---|
| Username and password | Trying things on your machine | Doesn’t work with SAML/SSO or MFA accounts; the password ends up in code or the environment. |
User authentication (OAuth 2.0, client_id alone) | Interactive scripts and apps | The refresh token expires, and changing the password invalidates it. |
| App credentials (used here) | Backend jobs, such as scheduled rotation | They need their owner’s user privileges, and the client_secret can do whatever those privileges allow. Both scripts use them. |
Create the credential item
API key credentials are items of type Application. title, tags and snippet match the wizard’s Item details screen. .result() waits for the item.
REST request
folder.add sends content/users/{user}/addItem and returns a job.
Register the item as an app
item.register sets what every key of this item can do:
privileges: the services the key can call, one per toggle on the wizard’s Privileges screen. See the privileges reference.http_referers: the domains allowed to use the key. Empty here so you can test from scripts or Postman.
Set your app’s URL as a referrer before you ship a public app. Without one, anyone who copies the key can use it from any site, billed to you. You can’t change referrers later without invalidating the key.
More details
- Sends
oauth2/registerApp. - Access to an item is the privilege
portal:app:access:item:<itemId>. app_typeandredirect_uriscome from OAuth 2.0 credentials:redirect_urisis where user authentication sends users back after they sign in.registerAppfails without them, but their values don’t affect the key.- The item now has a
client_idandclient_secretinitem.app_info. The secret can generate new keys: keep it out of apps.
Set the expiration of slot 1
Each item has two key slots, each with its own expiration date: at most one year ahead, in epoch milliseconds. Set it before generating the key: changing it later invalidates the key.
REST request
item.update sends content/users/{user}/items/{id}/update with the date as an item property.
Generate the API key
The response’s access_token is the key. The portal shows it only once: deploy it to your app. state.json keeps the item ID and slot for the rotation script, but not the key.
More details
item.generate_api_tokensendsoauth2/tokenwith the item’sclient_idandclient_secret,grant_type=client_credentials,apiToken=1andregenerateApiToken=false.- Organization administrators can do all of the above in one call with
gis.admin.developer_credentials.create(…).gis.adminexists only for theorg_adminrole, so this tutorial uses the item methods, which every Creator can call.
Rotate: start from the key in production
Rotation keeps a valid key at all times: generate a key in the free slot, deploy it, then invalidate the old one.
The script signs in with the same .env and reads the item and current slot from state.json.
Find the free slot
The new key goes into the slot that isn’t in production. Without state.json, A key ends in AT1_ or AT2_ plus eight characters..
Generate the key in the new slot
Set the slot’s expiration first, then generate with regenerate=True: without it, a slot that already holds a key refuses a new one. Regenerating kills the old key in that slot immediately, so never regenerate the slot in production.
Why set the expiration again
generate_api_token only writes the date when the slot has none. regenerate=True sends regenerateApiToken=true.
Deploy the new key
Put the new key in production. The old key stays valid until you continue.
Invalidate the old key
Item has no method to invalidate a key, so the script uses DeveloperCredential.revoke with the old slot, then saves the new slot to state.json for the next rotation.
If gis.admin.developer_credentials returns None
Despite its name, gis.admin doesn’t always need an administrator: on ArcGIS Online it works for app credentials that carry their owner’s user privileges. With fewer privileges it may return None. Then send oauth2/revokeToken yourself:
app = item.app_info
gis.session.post(
f"{gis.url}/sharing/rest/oauth2/revokeToken",
data={"f": "json", "client_id": app["client_id"],
"client_secret": app["client_secret"], "apiToken": current_slot},
)API keys suit public apps. A backend script can authenticate as an application instead: authenticate a Python script with OAuth credentials.