I need a Python script that uses ArcGIS REST API to upload a zip file and update a hosted feature service -- NOT using the arcgis package. I trying to follow Update.
Here's what I have so far -- but nothing is successfully posting or updating.
import requests
import json
import os
from datetime import datetime
now = datetime.now()
# dd/mm/YY H:M:S
dt_string = now.strftime("%m/%d/%Y")
# ArcGIS REST API URL for the item to be updated
item_id = "itemid"
url = f"https://myorg.maps.arcgis.com/sharing/rest/content/items/{item_id}/update"
# Get token
baseURL = "https://www.arcgis.com"
loginURL = "https://www.arcgis.com/sharing/rest/generateToken".format(baseURL)
username = "username"
password = "password"
expiration = 60
loginparams = {'username': username, 'password': password, 'client': 'referer', 'referer': baseURL, 'expiration': expiration, 'f': 'json'}
loginresponse = requests.post(loginURL, data=loginparams, verify=False)
token = loginresponse.json()['token']
# Path to the updated zipped shapefile
updated_shapefile_path = "C:\\GIS\\myzip.zip"
# Prepare the request headers
headers = {
"Content-Type": "multipart/form-data",
}
# Prepare the request parameters
params = {
"f": "json",
"title": f"My layer {dt_string}",
"description": f"My description - Last downloaded {dt_string}",
"snippet": f"My snippet - Last updated {dt_string}",
"token": token
}
# Open the shapefile in binary mode
with open(updated_shapefile_path, "rb") as file:
files = {"file": (os.path.basename(updated_shapefile_path), file)}
try:
response = requests.post(url, params=params, headers=headers, files=files)
response.raise_for_status()
if response.status_code == 200:
print("Shapefile updated successfully.")
else:
print(f"Failed to update shapefile. Status code: {response.status_code}")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"Error during shapefile update: {e}")
# Check the response
if response.status_code == 200:
print("Shapefile updated successfully.")
else:
print(f"Failed to update shapefile. Status code: {response.status_code}")
print(response.text)