Skip to content

Instantly share code, notes, and snippets.

@YikChingTsui
Created April 24, 2024 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YikChingTsui/ff6d7b6126db73a77e5845576250177d to your computer and use it in GitHub Desktop.
Save YikChingTsui/ff6d7b6126db73a77e5845576250177d to your computer and use it in GitHub Desktop.
Get token for ArcGIS REST API, for addFeatures, applyEdits, etc.
from urllib.parse import urlencode
import requests
from flask import Flask, request
# fill in the client id
client_id = 'client_id'
redirect_uri = 'https://localhost:1111'
port = 1111
params = urlencode({
'client_id': client_id,
'response_type': 'code',
'redirect_uri': redirect_uri
})
# fill in your portal url
authorize_url = 'https://your-portal.com/sharing/rest/oauth2/authorize?' + params
print('Go to this link in your browser')
print(authorize_url)
token_url = "https://your-portal.com/sharing/rest/oauth2/token"
app = Flask(__name__)
@app.route("/")
def callback():
code = request.args.get("code")
if code:
token_params = {
"grant_type": "authorization_code",
"code": code,
"client_id": client_id,
"redirect_uri": redirect_uri,
}
response = requests.post(token_url, data=token_params)
if response.status_code == 200:
j = response.json()
access_token = j.get("access_token")
if access_token is not None:
print(f"Access token: {access_token}")
return "Authentication successful. You can close this window."
else:
print(j)
return "Error getting access token."
else:
print(f"Access token request failed: {response.text}")
return "Access token request failed."
else:
return "No code received."
if __name__ == "__main__":
app.run(host="localhost", port=port, ssl_context="adhoc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment