To begin with
ArcGIS API for Python is a Python library for automating Web GIS. The23rdsessionGISCommunity Forum focused on automating operations in ArcGIS Online was held.
About the session
From Wednesday, May 27 to Friday, May 29, 2026, in Roppongi, Tokyo Midtownthe "23rd GIS Community Forum"was held.
Here is a summary of the entire forum.
In the final session on the 29th at 15:55 titled "ArcGIS API for Python Basics: Introduction to Web GIS Operations and Automation," we introduced some basic content and several tips about ArcGIS API for Python, which is a library for automating Web GIS.
The tips mainly introduced content that was actually implemented, but there were requests such as "I want to be able to do similar things" and "I want to see more sample code," so I decided to explain them in this article.
ArcGIS API for Python is a Python-based API that can automate operations of ArcGIS Online and ArcGIS Enterprise.
For basic explanations about ArcGIS API for Python, please refer to this series of articles.
Contents covered in this article
This article explains the tips introduced in the session using demos in order.
- Sign In (Authentication)
- Bulk Deletion of Folders and Items
Scheduled Execution
- Contents for Scheduled Execution
- Usage of Feature Layer Usage of Feature Layer
- Script to Update Feature Layer
- Preparation for Authentication Item
- Task Settings
- Authentication
- Notes when Sharing
Sign In (Authentication)
First, Sign In is necessary to access essential ArcGIS functions such as private items or base maps. The following slides explain it.
With ArcGIS API for Python, after authentication, you can access public content and your private content to perform operations. In environments connected to ArcGIS such as ArcGIS Pro or ArcGIS Online where you are signed in, you can easily authenticate with GIS("home").
ArcGIS Pro's Python window
ArcGIS Online / ArcGIS Enterprise notebook block
Environment running python.exe in ArcGIS Pro's clone environment
Environments like Google Colab or those without ArcGIS Pro installed cannot use GIS("home"), so you need to authenticate using ID and password or API key. There are many other authentication methods besides the one introduced here; if interested, please refer to the GIS module reference.
Below are examples showing some information of a private user authenticated by API key.
#API key authentication
gis = GIS(api_key="<YOUR_API_KEY>",referer="https")
#Display GIS object
print(gis)
#Display user info
print(gis.users.me)
#Display private item info
myItem = gis.content.get("<Item ID>")
myItem
Bulk Deletion of Folders and Items
Continuing with bulk deletion of folders and items.
In the session, we introduced a video showing how to delete folders and their contents all at once, but as in the following code, we executed it using the Folders classFolder class. Here we retrieve folders one by one, display folder names if not Root Folder and delete them; folders that cannot be deleted are finally deleted only by deleting items.
GIS モジュールの search メソッドで所有アイテムを検索し、アイテムを全て削除してからフォルダーを削除する方法でも同様の作業が実行できます。
定期実行
定期実行させる内容
この項では以下のような流れで外部 API と連携した Feature Layer の更新を行います。
次のセクションから各手順を説明します。
Feature Layer の用意
最初の手順として、更新するための材料を用意します。 以下のようなスクリプトで API から取得した情報を処理し、更新用データを作成します。 ここでは ArcGIS Online のノートブックで実行することを想定しています。 ※ArcGIS Online のノートブックの詳しい使い方はこちらを参照してください。
実行する時は ArcGIS Online のノートブックで新しいノートブックを Standard で作成し、1 セル目に上書きするように貼り付けてください。
from arcgis.gis import GIS
from arcgis.features import FeatureLayerCollection
import requests
import time
# 1) 接続(ここでは home で認証する)
gis = GIS("home")
# 2) ISS API から取得
ISS_URL = "http://api.open-notify.org/iss-now.json" # [1](http://open-notify.org/Open-Notify-API/ISS-Location-Now/)
def fetch_iss():
r = requests.get(ISS_URL, timeout=30)
r.raise_for_status()
data = r.json()
lat = float(data["iss_position"]["latitude"])
lon = float(data["iss_position"]["longitude"])
ts_sec = int(data["timestamp"])
ts_ms = ts_sec * 1000
return lat, lon, ts_ms
# 3) Hosted Feature Service 作成
SERVICE_NAME = "ISS_Last3Points"
service_item = gis.content.create_service(
name=SERVICE_NAME,
service_type="featureService"
)
flc = FeatureLayerCollection.fromitem(service_item)
# 4) レイヤー定義
layer_def = {
"layers": [{
"name": "<作成する Feature Layer の名前>",
"type": "Feature Layer",
"geometryType": "esriGeometryPoint",
"spatialReference": {"wkid": 4326},
"objectIdField": "ObjectID",
"fields": [
{"name": "ObjectID", "type": "esriFieldTypeOID", "alias": "ObjectID"},
{"name": "latitude", "type": "esriFieldTypeDouble", "alias": "latitude"},
{"name": "longitude", "type": "esriFieldTypeDouble", "alias": "longitude"},
{"name": "obs_time", "type": "esriFieldTypeDate", "alias": "obs_time"},
]
}]
}
# 5) 定義をサービスに追加
flc.manager.add_to_definition(layer_def)
layer = flc.layers[0]
# 6) 初期 3 件投入(ISS API 推奨に考慮して 5 秒間隔)
adds = []
for i in range(3):
lat, lon, ts_ms = fetch_iss()
adds.append({
"geometry": {"x": lon, "y": lat, "spatialReference": {"wkid": 4326}},
"attributes": {"latitude": lat, "longitude": lon, "obs_time": ts_ms}
})
if i < 2:
time.sleep(5) # ポーリング過多を避ける [1](http://open-notify.org/Open-Notify-API/ISS-Location-Now/)
res = layer.edit_features(adds=adds)
print("作成したアイテム ID:", service_item.id)
print("レイヤーURL:", layer.url)
print("追加結果:", res)
実行が終わるとこのようにアイテムが作られます。スクリプトで指定した名前でアイテムが作成されていることを確認します。
これで更新用データの用意はできました。
Feature Layer を更新するスクリプト
先ほど作成したアイテムの ID を使って更新をします。 アイテム ページの [URL] の下の下矢印を開いてアイテム ID を探します。
次に、以下のスクリプトを使用してデータの更新を行います。 ここでは 3 件あるフィーチャのうち、最も古いものを削除し、取得したデータを新たに追加するように処理しています。新しく Standard でノートブックを作成し、データ作成時と同じように 1 セル目に上書きするように貼り付けてください。
from arcgis.gis import GIS
import requests
gis = GIS("home")
ITEM_ID = "<作成したアイテム ID>"
ISS_URL = "http://api.open-notify.org/iss-now.json"
def fetch_iss():
r = requests.get(ISS_URL, timeout=30)
r.raise_for_status()
data = r.json()
lat = float(data["iss_position"]["latitude"])
lon = float(data["iss_position"]["longitude"])
ts_sec = int(data["timestamp"])
ts_ms = ts_sec * 1000
return lat, lon, ts_ms
# 1) Retrieve layer
item = gis.content.get(ITEM_ID)
layer = item.layers[0]
# 2) Retrieve existing 3 items in chronological order (oldest first)
# order_by_fields corresponds to REST's orderByFields parameter
fset = layer.query(
where="1=1",
out_fields="ObjectID,obs_time",
order_by_fields="obs_time ASC"
)
features = fset.features
# 3) If there are 3 or more items, delete the oldest one
if len(features) >= 3:
oldest_oid = features[0].attributes.get("ObjectID")
# deletes parameter of edit_features basically requires a comma-separated string of OIDs [10](https://gis.stackexchange.com/questions/278263/arcgis-api-for-python-delete-multiple-features)
del_res = layer.edit_features(deletes=str(oldest_oid))
print("Deleted:", del_res)
# 4) Add 1 new item
lat, lon, ts_ms = fetch_iss()
new_feature = {
"geometry": {"x": lon, "y": lat, "spatialReference": {"wkid": 4326}},
"attributes": {"latitude": lat, "longitude": lon, "obs_time": ts_ms}
}
add_res = layer.edit_features(adds=[new_feature])
print("Added:", add_res)
# 5) Confirm current count
cur_cnt = layer.query(where="1=1", return_count_only=True)
print("Current count:", cur_cnt)
When execution succeeds, messages about deletion and update will be displayed as below.
This completes the preparation of the script for updating. Next, we will create an item to verify the update.
Preparation for verification item
First, create a Web Map. Open the Feature Layer's item in Map Viewer and from [Save As], [] click [Save with name] to create a Web Map.
Once updated, you can reload the map and verify the update. Also, by opening the Feature Layer settings from the Web Map and turning on the "Automatically update layer" check, you can verify updates without reloading the browser.
Below is an example of execution.
Next, set up periodic updates for the created point.
Task settings
Note: During task execution, credits are consumed according to execution time.