An API key is a long-lived access token that authorizes your application to access secure services, content, and functionality in ArcGIS.
This tutorial shows you how to use the arcgis-rest-developer-credentials
module in ArcGIS REST JS to programmatically create API key credentials and do the following:
- Generate long-lived API keys and save them in your application.
- Configure privileges to allow your API keys to access ArcGIS services, content, and functionality.
- Set the expiration date of an API key.
- Manage API keys.
Prerequisites
An ArcGIS Location Platform, ArcGIS Online, or ArcGIS Enterprise account. Your account must also have a user type of Creator or higher and the correct permissions. To learn more, go to Product and account requirements.
Steps
Set up the project
This tutorial uses ArcGIS REST JS with Node.js to create a standalone console script. Set up the project directory and install the necessary packages.
-
Create a new directory using a code editor of your choice.
-
Set up a Node JS project and install the following packages using npm or yarn:
@esri/arcgis-rest-developer-credentials
@esri/arcgis-rest-request
@esri/arcgis-rest-portal
dotenv
-
Create a main file called
index.js
. Import methods from ArcGIS REST JS.index.jsUse dark colors for code blocks import { createApiKey } from "@esri/arcgis-rest-developer-credentials"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; import { moveItem, getSelf } from "@esri/arcgis-rest-portal";
Set environment variables
Set up environment variables to store information about your ArcGIS account.
-
Create a new file named
.env
. -
Add the following variables to the file. Replace
"
andYOUR _ACCOUNT _USERNAM E" "
with your ArcGIS account credentials. If you are using ArcGIS Enterprise, updateYOUR _ACCOUNT _PASSWOR D" "
with your portal's REST endpoint. Otherwise, you can omit this field.PORTAL _UR L" .envUse dark colors for code blocks ARCGIS_USERNAME="YOUR_ACCOUNT_USERNAME" ARCGIS_PASSWORD="YOUR_ACCOUNT_PASSWORD" PORTAL_URL="https://{machine.domain.com}/{webadaptor}/sharing/rest" # OPTIONAL - For Enterprise accounts only
-
Save the file.
Configure authentication
-
Load the environment variables by importing
dotenv/config
. ConfigureArcGIS
with the username, password, and portal URL to set up authentication for the script.Identity Manager index.jsUse dark colors for code blocks import "dotenv/config"; const authentication = await ArcGISIdentityManager.signIn({ username: process.env.ARCGIS_USERNAME, password: process.env.ARCGIS_PASSWORD, portal: process.env.PORTAL_URL // OPTIONAL - For ArcGIS Enterprise only });
-
Call
get
to get the URL of your organization, which will be needed in a later step.Self Use dark colors for code blocks const authentication = await ArcGISIdentityManager.signIn({ username: process.env.ARCGIS_USERNAME, password: process.env.ARCGIS_PASSWORD, portal: process.env.PORTAL_URL // OPTIONAL - For ArcGIS Enterprise only }); const orgUrl = await getSelf({ authentication: authentication });
Create an API key credential
Generate an API key programmatically using ArcGIS REST JS. You will define key properties such as its title, description, and tags, then set privileges and an expiration date.
-
Using
create
, generate a new API key credential with the following properties:Api Key - Title:
AP
I key ${ Math.floor( Date.now() / 1000)} - Description:
AP
I Key generated with ArcGI S RES T J S with spatial analysis and basemap privileges - Tags:
api key
,basemaps
,spatial analysis
,authentication
- Generate token 1:
true
Use dark colors for code blocks const newKey = await createApiKey({ title: `API key ${Math.floor(Date.now() / 1000)}`, description: "API Key generated with ArcGIS REST JS with spatial analysis and basemap privileges", tags: ["api key", "basemaps", "spatial analysis", "authentication"], generateToken1: true, authentication: authentication });
- Title:
-
Set the privileges for the API key credential. The specific privileges required by your key depend on your use case. To view all available privileges, go to Privileges.
Use dark colors for code blocks const newKey = await createApiKey({ title: `API key ${Math.floor(Date.now() / 1000)}`, description: "API Key generated with ArcGIS REST JS with spatial analysis and basemap privileges", tags: ["api key", "basemaps", "spatial analysis", "authentication"], privileges: [ "premium:user:spatialanalysis", "premium:user:basemaps" // Not available for ArcGIS Enterprise ], generateToken1: true, authentication: authentication });
-
Specify the expiration date for the API key you are generating.
Use dark colors for code blocks const newKey = await createApiKey({ title: `API key ${Math.floor(Date.now() / 1000)}`, description: "API Key generated with ArcGIS REST JS with spatial analysis and basemap privileges", tags: ["api key", "basemaps", "spatial analysis", "authentication"], privileges: [ "premium:user:spatialanalysis", "premium:user:basemaps" // Not available for ArcGIS Enterprise ], generateToken1: true, apiToken1ExpirationDate: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30), // 30 days authentication: authentication });
-
Once the operation is complete, an API key credential will be created as an item in your portal. You can access the item ID and other properties of the object, including all API keys associated with the item. The API key 1 generated here should be stored for use in other requests.
Use dark colors for code blocks const newKey = await createApiKey({ title: `API key ${Math.floor(Date.now() / 1000)}`, description: "API Key generated with ArcGIS REST JS with spatial analysis and basemap privileges", tags: ["api key", "basemaps", "spatial analysis", "authentication"], privileges: [ "premium:user:spatialanalysis", "premium:user:basemaps" // Not available for ArcGIS Enterprise ], generateToken1: true, apiToken1ExpirationDate: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30), // 30 days authentication: authentication }); console.log(`\nNew API key created: ${newKey.accessToken1}`); console.log(`\nView item: https://${orgUrl.urlKey}.maps.arcgis.com/home/item.html?id=${newKey.itemId}`);
Manage your credential (optional)
To keep your credentials organized, it is a best practice to store all API key credentials in a designated folder. You can move the credential to a specific folder in your portal using move
.
-
Use the following code to move the newly created API key into a folder dedicated to storing API key credentials.
Use dark colors for code blocks const moved = await moveItem({ itemId: newKey.itemId, folderId: "YOUR_FOLDER_ID", authentication: authentication }); console.log(`\nItem moved ${JSON.stringify(moved)}`);
-
You can also use
update
to modify the API key credential, such as:Api Key - Reassigning privileges
- Assigning item access using
portal
:app :access :item :{ ITEM _I D} - Changing the API key expiration date
- Generating a secondary access token
Run the app
Run the app.
After running the script, you should see the generated access token printed in the console, along with a URL to view the API key credential item in your portal.