Select to view content in your preferred language

How to programmatically check API key expiration

1526
1
01-13-2025 12:02 PM
jdyerLACSD
Occasional Contributor

I'd like to write a Python script to run periodically and check the expiration date of my API keys, then email me about any that are expiring soon.  Currently, I can't figure out how to accomplish this with the ArcGIS Python API.

  • I tried using gis.api_keys.keys, but that only shows the old (deprecated) API keys
  • Then I tried gis.content.search("type:application"), which successfully fetches the new API key (developer credentials) items, plus all other application items.  It looked like the property "apiToken1ExpirationDate" would be the place to get the expiration dates, but it only returns the correct expiration date occasionally. Most of the time, it returns -1 instead.

Is there another way to get the expiration date for developer credential API keys?

0 Kudos
1 Reply
GavinRehkemper
Esri Contributor

Hi John,

I do think the "apiToken1ExpirationDate" and "apiToken2ExpirationDate" properties are what you want, but it does look like you need to check if the token is valid first using the "registeredAppInfo" endpoint, using the "apiToken1Active" and "apiToken2Active" properties. Putting that all together into a simple Python script would look like this:

from arcgis.gis import GIS
from datetime import datetime
gis = GIS("home")
item = gis.content.get("API_KEY_ITEM_ID")
print(f"slot 1 expiration: {datetime.fromtimestamp(item.apiToken1ExpirationDate/1000).strftime('%B %d %Y at %I:%M.%S %p') if item.app_info.get("apiToken1Active") else 'None'}")
print(f"slot 2 expiration: {datetime.fromtimestamp(item.apiToken2ExpirationDate/1000).strftime('%B %d %Y at %I:%M.%S %p') if item.app_info.get("apiToken2Active") else 'None'}")
0 Kudos