# Create and rotate an API key with REST requests

> No SDK. Script the four requests the portal sends behind the scenes, then rotate the key with its two slots. Pick cURL or Python requests.

Interactive version: http://www.rauljimenez.info/arcgis-tutorials/api-key-rest/?variant=curl

Code variant: cURL. Other variants: [Python](http://www.rauljimenez.info/arcgis-tutorials/api-key-rest/tutorial.python.md).

## What you will build

Two scripts, in cURL or Python (pick one in the code header):

* `create-api-key.sh` / `create_api_key.py` creates the API key credentials and generates the first key, in slot 1.
* `rotate-api-key.sh` / `rotate_api_key.py` rotates that key without downtime, using the second slot.

They send the same requests as the portal's [**New item › Developer credentials** wizard](../api-key-portal/#add-item), so every parameter matches a field in the wizard.

<details>
<summary>Check prerequisites</summary>
<p>An ArcGIS Location Platform, ArcGIS Online, or ArcGIS Enterprise account with a Creator user type or higher and the <strong>Generate API keys</strong> and <strong>Assign privileges to OAuth 2.0 applications</strong> privileges. Ideally a service user with only those.</p>
<p>cURL version: <code>bash</code>, <code>curl</code> and <code>jq</code>. Python version: Python 3 with <code>requests</code> and <code>python-dotenv</code>.</p>
</details>

> 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 sharing API (`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.):

- **Portal URL** (`portalUrl`)

`ITEM_OWNER` is the username in the item URLs:

- **Username (owner of the item)** (`username`)

The scripts sign in with app credentials (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:

- **App credentials client ID** (`appClientId`)
- **App credentials client secret** (`appClientSecret`)

> **Keep the `client_secret` in 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.

<details>
<summary>More details</summary>
<ul>
<li>The variable is <code>ITEM_OWNER</code>, not <code>USERNAME</code>, because Windows already sets <code>USERNAME</code>.</li>
<li>Creating and rotating keys with app credentials needs their owner's user privileges: on ArcGIS Location Platform, <code>createItem</code>, <code>generateApiTokens</code> and <code>assignPrivilegesToApps</code> alone were not enough. The secret can't sign in or change your password, but it can do whatever those privileges allow.</li>
<li>In production, the same variables can come from the environment or a secret manager instead of <code>.env</code>.</li>
<li>Without <code>VERBOSE=1</code>, the scripts print only the item ID and the key.</li>
</ul>
</details>

```text title="code/curl/.env.example" region="config"
# Configure the scripts: copy this file to .env and fill it in
PORTAL="https://www.arcgis.com/sharing/rest"
# Owner of the API key item
ITEM_OWNER="YOUR_USERNAME"
# App credentials of a service user, with that user's privileges (not the API key item's)
APP_CLIENT_ID="YOUR_APP_CLIENT_ID"
APP_CLIENT_SECRET="YOUR_APP_CLIENT_SECRET"
```

## 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`.

<details>
<summary>Other ways to sign in</summary>
<p>Get the token from <code>generateToken</code> (username and password) or from the OAuth 2.0 authorization code flow; everything after this step stays the same.</p>
<table>
<tr><th>Method</th><th>Use it for</th><th>Limits</th></tr>
<tr><td>Username and password</td><td>Trying things on your machine</td><td>Doesn't work with SAML/SSO or MFA accounts; the password ends up in code or the environment.</td></tr>
<tr><td><a href="https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/">User authentication</a> (OAuth 2.0)</td><td>Interactive scripts and apps</td><td>The refresh token expires, and changing the password invalidates it.</td></tr>
<tr><td><a href="https://developers.arcgis.com/documentation/security-and-authentication/app-authentication/">App credentials</a></td><td>Backend jobs, such as scheduled rotation</td><td>They need their owner's user privileges, and the <code>client_secret</code> can do whatever those privileges allow. Both scripts use them.</td></tr>
</table>
</details>

```bash title="code/curl/create-api-key.sh" region="sign-in"
# Sign in
source .env
TOKEN=$(curl -s -X POST "$PORTAL/oauth2/token" \
  -d client_id="$APP_CLIENT_ID" \
  -d client_secret="$APP_CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d f=json | log | jq -r .access_token)
```

## Create the credential item

`addItem` creates an empty item of type `Application`. `title`, `tags` and `snippet` match the wizard's [**Item details**](../api-key-portal/#details) screen. Its `id` goes into the next two requests.

```bash title="code/curl/create-api-key.sh" region="add-item"
# Create the credential item
# Portal wizard › Item details: title, tags and description
ITEM_ID=$(curl -s -X POST "$PORTAL/content/users/$ITEM_OWNER/addItem" \
  -d type=Application \
  --data-urlencode title="My API key credentials tutorial" \
  --data-urlencode tags="api key,basemaps,geocoding" \
  --data-urlencode snippet="Key for the store locator app" \
  -d token="$TOKEN" \
  -d f=json | log | jq -r .id)
```

## 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**](../api-key-portal/#register) screen. See the [privileges reference](https://developers.arcgis.com/documentation/security-and-authentication/reference/privileges/).
- `httpReferrers`: the domains allowed to use the key. Empty here so you can test from scripts or Postman.

- **Privileges (comma-separated)** (`privileges`)

> **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_secret` is the master credential.** Anyone with it can generate new keys for this item: keep it out of apps and repositories.

<details>
<summary>More details</summary>
<ul>
<li><a href="../api-key-portal/#item-access">Access to an item</a> is the privilege <code>portal:app:access:item:&lt;itemId&gt;</code>.</li>
<li><code>appType</code> and <code>redirect_uris</code> come from OAuth 2.0 credentials: <code>redirect_uris</code> is where <a href="https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/">user authentication</a> sends users back after they sign in. <code>registerApp</code> fails without them, but their values don't affect the key (even <code>redirect_uris=[]</code> works).</li>
</ul>
</details>

```bash title="code/curl/create-api-key.sh" region="register"
# Register the item as an app
# Portal wizard › Privileges: services the key can call (+ portal:app:access:item:<id> per item)
PRIVILEGES="premium:user:basemaps,premium:user:geocode"

# Portal wizard › Settings: httpReferrers empty = any site can use the key. Set your app's URL(s) before you ship
APP=$(curl -s -X POST "$PORTAL/oauth2/registerApp" \
  -d itemId="$ITEM_ID" \
  -d appType=multiple \
  --data-urlencode 'redirect_uris=["urn:ietf:wg:oauth:2.0:oob"]' \
  --data-urlencode "privileges=$(jq -cn --arg p "$PRIVILEGES" '$p | split(",") | map(gsub("^ +| +$"; ""))')" \
  --data-urlencode 'httpReferrers=[]' \
  -d token="$TOKEN" \
  -d f=json | log)
CLIENT_ID=$(echo "$APP" | jq -r .client_id)
CLIENT_SECRET=$(echo "$APP" | jq -r .client_secret)
```

## 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.

```bash title="code/curl/create-api-key.sh" region="expiration"
# Set the expiration of slot 1
# Portal wizard › Settings: expiration date (max. 1 year)
EXPIRES=$(( ($(date +%s) + 30 * 86400) * 1000 )) # 30 days from now, epoch ms
curl -s -X POST "$PORTAL/content/users/$ITEM_OWNER/items/$ITEM_ID/update" \
  -d apiToken1ExpirationDate="$EXPIRES" \
  -d token="$TOKEN" \
  -d f=json | log >/dev/null
```

## 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.

<details>
<summary>More details</summary>
<ul>
<li>The <code>client_secret</code> authenticates this call; no user token is sent. Without <code>apiToken</code>, the same request returns a two-hour app token instead.</li>
<li><code>regenerateApiToken</code> is a safety switch. On an empty slot it can be <code>false</code>, <code>true</code> or left out. On a slot that already holds a key, <code>false</code> fails with <code>400 Unauthorized</code>, and <code>true</code> replaces the key.</li>
</ul>
</details>

```bash title="code/curl/create-api-key.sh" region="generate"
# Generate the API key
# Portal wizard › Generate API key: generate the key in slot 1 now
API_KEY=$(curl -s -X POST "$PORTAL/oauth2/token" \
  -d client_id="$CLIENT_ID" \
  -d client_secret="$CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d apiToken=1 \
  -d regenerateApiToken=false \
  -d f=json | log | jq -r .access_token)

echo "Item ID: $ITEM_ID"
echo "API key (slot 1): $API_KEY"

# state.json is written by the scripts, unlike .env. It doesn't hold the key: deploy that to your app
# state.json: {"itemId": "a1f3c9e27b8d4e6f9c0b2d4e6f8a1c3e", "slot": 1}
jq -n --arg id "$ITEM_ID" '{itemId: $id, slot: 1}' > state.json
```

## 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`.

```bash title="code/curl/rotate-api-key.sh" region="rotate-config"
# Rotate: start from the key in production
source .env
# Item and slot of the key in production, saved by create-api-key.sh
# state.json: {"itemId": "a1f3c9e27b8d4e6f9c0b2d4e6f8a1c3e", "slot": 1}
ITEM_ID=$(jq -r .itemId state.json)
CURRENT_SLOT=$(jq -r .slot 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.

```bash title="code/curl/rotate-api-key.sh" region="app-info"
TOKEN=$(curl -s -X POST "$PORTAL/oauth2/token" \
  -d client_id="$APP_CLIENT_ID" \
  -d client_secret="$APP_CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d f=json | log | jq -r .access_token)

APP=$(curl -s -X POST "$PORTAL/content/users/$ITEM_OWNER/items/$ITEM_ID/registeredAppInfo" \
  -d token="$TOKEN" \
  -d f=json | log)
CLIENT_ID=$(echo "$APP" | jq -r .client_id)
CLIENT_SECRET=$(echo "$APP" | jq -r .client_secret)
```

## Find the free slot

The new key goes into the slot that isn't in production. Without `state.json`, the key tells you its slot (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`.).

```bash title="code/curl/rotate-api-key.sh" region="find-slot"
if [ "$CURRENT_SLOT" = "2" ]; then NEW_SLOT=1; else NEW_SLOT=2; fi
```

## 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.

```bash title="code/curl/rotate-api-key.sh" region="rotate-expiration"
EXPIRES=$(( ($(date +%s) + 30 * 86400) * 1000 )) # 30 days from now, epoch ms
curl -s -X POST "$PORTAL/content/users/$ITEM_OWNER/items/$ITEM_ID/update" \
  -d "apiToken${NEW_SLOT}ExpirationDate=$EXPIRES" \
  -d token="$TOKEN" \
  -d f=json | log >/dev/null
```

## 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.

```bash title="code/curl/rotate-api-key.sh" region="rotate-generate"
NEW_KEY=$(curl -s -X POST "$PORTAL/oauth2/token" \
  -d client_id="$CLIENT_ID" \
  -d client_secret="$CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d apiToken="$NEW_SLOT" \
  -d regenerateApiToken=true \
  -d f=json | log | jq -r .access_token)
echo "New API key (slot $NEW_SLOT): $NEW_KEY"
```

## Deploy the new key

Put the new key in production. The old key stays valid until you continue.

```bash title="code/curl/rotate-api-key.sh" region="deploy"
read -r -p "Deploy the new key, then press Enter to invalidate the old one…"
```

## 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`.

<details>
<summary>Parameters ArcGIS REST JS adds</summary>
<p>ArcGIS REST JS also sends <code>grant_type</code> and <code>regenerateApiToken</code>, but <code>client_id</code>, <code>client_secret</code> and <code>apiToken</code> are all it needs.</p>
</details>

```bash title="code/curl/rotate-api-key.sh" region="invalidate"
SUCCESS=$(curl -s -X POST "$PORTAL/oauth2/revokeToken" \
  -d client_id="$CLIENT_ID" \
  -d client_secret="$CLIENT_SECRET" \
  -d apiToken="$CURRENT_SLOT" \
  -d f=json | log | jq -r .success)
echo "Old key in slot $CURRENT_SLOT invalidated: $SUCCESS"

# The key in production is now in the new slot
jq -n --arg id "$ITEM_ID" --argjson slot "$NEW_SLOT" '{itemId: $id, slot: $slot}' > state.json
```

You scripted the four requests yourself. A library can send them for you:

- Used Python? [ArcGIS API for Python](../api-key-python-api/) wraps each request in one `Item` method.
- Used cURL? Try [ArcGIS API for Python](../api-key-python-api/) or [ArcGIS REST JS](../api-key-rest-js/) for Node.js.

## Final code

### code/curl/.env.example

```text title="code/curl/.env.example"
# Configure the scripts: copy this file to .env and fill it in
PORTAL="https://www.arcgis.com/sharing/rest"
# Owner of the API key item
ITEM_OWNER="YOUR_USERNAME"
# App credentials of a service user, with that user's privileges (not the API key item's)
APP_CLIENT_ID="YOUR_APP_CLIENT_ID"
APP_CLIENT_SECRET="YOUR_APP_CLIENT_SECRET"
```

### code/curl/create-api-key.sh

```bash title="code/curl/create-api-key.sh"
#!/usr/bin/env bash
# Create API key credentials and generate the first API key (slot 1).
# Requires curl and jq.

# Print each response when VERBOSE=1. They include secrets: don't enable it where logs are kept
log() {
  local response
  response=$(cat)
  if [ -n "$VERBOSE" ]; then jq . <<<"$response" >&2; fi
  printf '%s\n' "$response"
}

# Sign in
source .env
TOKEN=$(curl -s -X POST "$PORTAL/oauth2/token" \
  -d client_id="$APP_CLIENT_ID" \
  -d client_secret="$APP_CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d f=json | log | jq -r .access_token)

# Create the credential item
# Portal wizard › Item details: title, tags and description
ITEM_ID=$(curl -s -X POST "$PORTAL/content/users/$ITEM_OWNER/addItem" \
  -d type=Application \
  --data-urlencode title="My API key credentials tutorial" \
  --data-urlencode tags="api key,basemaps,geocoding" \
  --data-urlencode snippet="Key for the store locator app" \
  -d token="$TOKEN" \
  -d f=json | log | jq -r .id)

# Register the item as an app
# Portal wizard › Privileges: services the key can call (+ portal:app:access:item:<id> per item)
PRIVILEGES="premium:user:basemaps,premium:user:geocode"

# Portal wizard › Settings: httpReferrers empty = any site can use the key. Set your app's URL(s) before you ship
APP=$(curl -s -X POST "$PORTAL/oauth2/registerApp" \
  -d itemId="$ITEM_ID" \
  -d appType=multiple \
  --data-urlencode 'redirect_uris=["urn:ietf:wg:oauth:2.0:oob"]' \
  --data-urlencode "privileges=$(jq -cn --arg p "$PRIVILEGES" '$p | split(",") | map(gsub("^ +| +$"; ""))')" \
  --data-urlencode 'httpReferrers=[]' \
  -d token="$TOKEN" \
  -d f=json | log)
CLIENT_ID=$(echo "$APP" | jq -r .client_id)
CLIENT_SECRET=$(echo "$APP" | jq -r .client_secret)

# Set the expiration of slot 1
# Portal wizard › Settings: expiration date (max. 1 year)
EXPIRES=$(( ($(date +%s) + 30 * 86400) * 1000 )) # 30 days from now, epoch ms
curl -s -X POST "$PORTAL/content/users/$ITEM_OWNER/items/$ITEM_ID/update" \
  -d apiToken1ExpirationDate="$EXPIRES" \
  -d token="$TOKEN" \
  -d f=json | log >/dev/null

# Generate the API key
# Portal wizard › Generate API key: generate the key in slot 1 now
API_KEY=$(curl -s -X POST "$PORTAL/oauth2/token" \
  -d client_id="$CLIENT_ID" \
  -d client_secret="$CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d apiToken=1 \
  -d regenerateApiToken=false \
  -d f=json | log | jq -r .access_token)

echo "Item ID: $ITEM_ID"
echo "API key (slot 1): $API_KEY"

# state.json is written by the scripts, unlike .env. It doesn't hold the key: deploy that to your app
# state.json: {"itemId": "a1f3c9e27b8d4e6f9c0b2d4e6f8a1c3e", "slot": 1}
jq -n --arg id "$ITEM_ID" '{itemId: $id, slot: 1}' > state.json
```

### code/curl/rotate-api-key.sh

```bash title="code/curl/rotate-api-key.sh"
#!/usr/bin/env bash
# Rotate an API key: generate a key in the free slot, deploy it, then invalidate the old one.
# Requires curl and jq.

# Print each response when VERBOSE=1. They include secrets: don't enable it where logs are kept
log() {
  local response
  response=$(cat)
  if [ -n "$VERBOSE" ]; then jq . <<<"$response" >&2; fi
  printf '%s\n' "$response"
}

# Rotate: start from the key in production
source .env
# Item and slot of the key in production, saved by create-api-key.sh
# state.json: {"itemId": "a1f3c9e27b8d4e6f9c0b2d4e6f8a1c3e", "slot": 1}
ITEM_ID=$(jq -r .itemId state.json)
CURRENT_SLOT=$(jq -r .slot state.json)

TOKEN=$(curl -s -X POST "$PORTAL/oauth2/token" \
  -d client_id="$APP_CLIENT_ID" \
  -d client_secret="$APP_CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d f=json | log | jq -r .access_token)

APP=$(curl -s -X POST "$PORTAL/content/users/$ITEM_OWNER/items/$ITEM_ID/registeredAppInfo" \
  -d token="$TOKEN" \
  -d f=json | log)
CLIENT_ID=$(echo "$APP" | jq -r .client_id)
CLIENT_SECRET=$(echo "$APP" | jq -r .client_secret)

if [ "$CURRENT_SLOT" = "2" ]; then NEW_SLOT=1; else NEW_SLOT=2; fi

EXPIRES=$(( ($(date +%s) + 30 * 86400) * 1000 )) # 30 days from now, epoch ms
curl -s -X POST "$PORTAL/content/users/$ITEM_OWNER/items/$ITEM_ID/update" \
  -d "apiToken${NEW_SLOT}ExpirationDate=$EXPIRES" \
  -d token="$TOKEN" \
  -d f=json | log >/dev/null

NEW_KEY=$(curl -s -X POST "$PORTAL/oauth2/token" \
  -d client_id="$CLIENT_ID" \
  -d client_secret="$CLIENT_SECRET" \
  -d grant_type=client_credentials \
  -d apiToken="$NEW_SLOT" \
  -d regenerateApiToken=true \
  -d f=json | log | jq -r .access_token)
echo "New API key (slot $NEW_SLOT): $NEW_KEY"

read -r -p "Deploy the new key, then press Enter to invalidate the old one…"

SUCCESS=$(curl -s -X POST "$PORTAL/oauth2/revokeToken" \
  -d client_id="$CLIENT_ID" \
  -d client_secret="$CLIENT_SECRET" \
  -d apiToken="$CURRENT_SLOT" \
  -d f=json | log | jq -r .success)
echo "Old key in slot $CURRENT_SLOT invalidated: $SUCCESS"

# The key in production is now in the new slot
jq -n --arg id "$ITEM_ID" --argjson slot "$NEW_SLOT" '{itemId: $id, slot: $slot}' > state.json
```

### code/curl/.gitignore

```text title="code/curl/.gitignore"
# Secrets (.env) and state written by the scripts
.env
state.json
```
