Following the Nest authorization documentation.
Get the values of Client ID and Client secret from the clients page and set them in the environment before running this IPython Notebook. The environment variable names should be DEN_CLIENT_ID
and DEN_CLIENT_SECRET
, respectively.
In [ ]:
import os
In [ ]:
DEN_CLIENT_ID = os.environ["DEN_CLIENT_ID"]
DEN_CLIENT_SECRET = os.environ["DEN_CLIENT_SECRET"]
Available per client. For Den it is:
https://home.nest.com/login/oauth2?client_id=54033edb-04e0-4fc7-8306-5ed6cb7d7b1d&state=STATE
Where STATE
should be a value that is:
STATE
helper
In [ ]:
import uuid
In [ ]:
def _get_state():
"""Get a unique id string."""
return str(uuid.uuid1())
In [ ]:
_get_state()
In [ ]:
API_PROTOCOL = "https"
API_LOCATION = "home.nest.com"
In [ ]:
from urlparse import SplitResult, urlunsplit
from urllib import urlencode
In [ ]:
def _get_url(path, query, netloc=API_LOCATION):
"""Get a URL for the given path and query."""
split = SplitResult(scheme=API_PROTOCOL, netloc=netloc, path=path, query=query, fragment="")
return urlunsplit(split)
In [ ]:
def get_auth_url(client_id=DEN_CLIENT_ID):
"""Get an authorization URL for the given client id."""
path = "login/oauth2"
query = urlencode({"client_id": client_id, "state": _get_state()})
return _get_url(path, query)
In [ ]:
get_auth_url()
In [ ]:
!open "{get_auth_url()}"
Cut and paste that PIN here:
In [ ]:
pin = ""
Use the pin
code to request an access token. https://developer.nest.com/documentation/cloud/authorization-reference/
In [ ]:
def get_access_token_url(client_id=DEN_CLIENT_ID, client_secret=DEN_CLIENT_SECRET, code=pin):
"""Get an access token URL for the given client id."""
path = "oauth2/access_token"
query = urlencode({"client_id": client_id,
"client_secret": client_secret,
"code": code,
"grant_type": "authorization_code"})
return _get_url(path, query, "api." + API_LOCATION)
In [ ]:
get_access_token_url()
POST
to that URL to get a response containing an access token:
In [ ]:
import requests
In [ ]:
r = requests.post(get_access_token_url())
print r.status_code
assert r.status_code == requests.codes.OK
In [ ]:
r.json()
It seems like the access token can only be created once and has a 10 year expiration time.
In [ ]:
access_token = r.json()["access_token"]
access_token
The access_token
will be used when making API calls.