What you will build
Two scripts, in cURL or Python (pick one in the code header):
create-api-key.sh/create_api_key.pycreates the API key credentials and generates the first key, in slot 1.rotate-api-key.sh/rotate_api_key.pyrotates that key without downtime, using the second slot.
They send the same requests as the portal’s New item › Developer credentials wizard, so every parameter matches a field in the wizard.
Check prerequisites
An ArcGIS Location Platform, ArcGIS Online, or ArcGIS Enterprise 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.
cURL version: bash, curl and jq. Python version: Python 3 with requests and python-dotenv.
Each Result pane shows what that step prints with
VERBOSE=1, captured earlier with made-up ids, secrets and keys. Nothing on this page sends a request.
Configure the scripts
Copy .env.example to .env and fill it in. .gitignore keeps it out of your repository.
Every request goes to the portal’s https://www.arcgis.com/sharing/rest for ArcGIS Online and ArcGIS Location Platform (your org URL works too), https://<host>/<web-adaptor>/sharing/rest for ArcGIS Enterprise.:
ITEM_OWNER is the username in the item URLs:
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.
Run with VERBOSE=1 (VERBOSE=1 bash create-api-key.sh or VERBOSE=1 python create_api_key.py) to print each response, as in the Result panes. It prints secrets: don’t use it in scheduled jobs whose output ends up in logs.
More details
- The variable is
ITEM_OWNER, notUSERNAME, because Windows already setsUSERNAME. - Creating and rotating keys with app credentials needs their owner’s user privileges: on ArcGIS Location Platform,
createItem,generateApiTokensandassignPrivilegesToAppsalone were not enough. 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. - Without
VERBOSE=1, the scripts print only the item ID and the key.
Sign in
oauth2/token with grant_type=client_credentials, the client ID and the secret returns an app token. Every request that follows sends it as token.
Other ways to sign in
Get the token from generateToken (username and password) or from the OAuth 2.0 authorization code flow; everything after this step stays the same.
| 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) | Interactive scripts and apps | The refresh token expires, and changing the password invalidates it. |
| App credentials | 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
addItem creates an empty item of type Application. title, tags and snippet match the wizard’s Item details screen. Its id goes into the next two requests.
Register the item as an app
registerApp turns the item into a credential and returns its client_id and client_secret. Two parameters set 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.httpReferrers: 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.
The
client_secretis the master credential. Anyone with it can generate new keys for this item: keep it out of apps and repositories.
More details
- Access to an item is the privilege
portal:app:access:item:<itemId>. appTypeandredirect_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 (evenredirect_uris=[]works).
Set the expiration of slot 1
Each item has two key slots, each with its own expiration date. The dates are item properties, so this is an item update, in epoch milliseconds, at most one year ahead.
Set it before generating the key: changing it later invalidates the key.
Generate the API key
oauth2/token with the item’s client credentials and apiToken=1 returns the key for slot 1 as access_token. 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
- The
client_secretauthenticates this call; no user token is sent. WithoutapiToken, the same request returns a two-hour app token instead. regenerateApiTokenis a safety switch. On an empty slot it can befalse,trueor left out. On a slot that already holds a key,falsefails with400 Unauthorized, andtruereplaces the key.
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 loads the same .env and reads the item and current slot from state.json.
Get the item’s client credentials
registeredAppInfo returns the item’s client_id and client_secret, so the script doesn’t need to keep them. apiToken1Active and apiToken2Active show which slots hold a key.
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, so the tenth character from the end is 1 or 2. ArcGIS REST JS reads it that way in slotForKey..
Set the expiration of the new slot
The same item update, now for apiToken2ExpirationDate (or apiToken1ExpirationDate when slot 2 is in use). Staggered dates let one key cover the other while it is replaced.
Generate the key in the new slot
The same oauth2/token request, with apiToken set to the new slot and regenerateApiToken=true in case it held an old key. Both keys are valid now.
Never regenerate the slot in production: its key dies the moment the new one is issued, and the app is down until you deploy.
Deploy the new key
Put the new key in production. The old key stays valid until you continue.
Invalidate the old key
revokeToken with the item’s client credentials and apiToken set to the old slot invalidates that key immediately. The script then saves the new slot to state.json.
Parameters ArcGIS REST JS adds
ArcGIS REST JS also sends grant_type and regenerateApiToken, but client_id, client_secret and apiToken are all it needs.
You scripted the four requests yourself. A library can send them for you:
- Used Python? ArcGIS API for Python wraps each request in one
Itemmethod. - Used cURL? Try ArcGIS API for Python or ArcGIS REST JS for Node.js.