how to get token to access a map service or feature service?

3442
3
06-24-2016 05:41 PM
BoYan
by
New Contributor II


I would like to access mao services for example this one: http://earthobs1.arcgis.com/arcgis/rest/services/Live_Stream_Gauges/MapServer/ , if I type the url in browser, it redirects me to the arcgis online login, then I can access the map server. But if I want to access the map server using python code with the REST API, how do I get the token?

I also noticed that there are many ways to get the token, like using 'Oauth2.0 token' or 'generateToken'. I just don't know what I should use and what exactly is the url I need to use to get the token in this case.

3 Replies
RandyBurton
MVP Regular Contributor

There is a link to some code in this blog article that gets a token: Using Python to push updates to a hosted feature service from an external source | ArcGIS Blog.  Here are the basic steps:

import urllib
import urllib2
import json

# Credentials and feature service information
username = '<username>'
password = '<password>'
URL = "<the services url you want to connect to>"
   
# obtain a token
referer = "http://www.arcgis.com/"
query_dict = { 'username': username, 'password': password, 'referer': referer }

query_string = urllib.urlencode(query_dict)
url = "https://www.arcgis.com/sharing/rest/generateToken"
token = json.loads(urllib.urlopen(url + "?f=json", query_string).read())

if "token" not in token:
    print(token['error'])
    sys.exit(1)

query_dict = { "f": "json", "token": token['token'] }

# query your services url
jsonResponse = urllib.urlopen(URL, urllib.urlencode(query_dict))

0 Kudos
BoYan
by
New Contributor II

thanks, I haven't tried your approach yet, but I figured that I can create an application in my developer account and use the app id and secret to get token for the rest api

JamalNUMAN
Esteemed Contributor

How to enable token for a particular map service?

----------------------------------------
Jamal Numan
Geomolg Geoportal for Spatial Information
Ramallah, West Bank, Palestine