Brosteins

Developers, Technology Evangelists, Bros.

Beginning with the Nest API

Recently I purchased a Nest Thermostat.  I had been wanting one for quite some time and the price was finally right.  After quickly getting my Nest up and running I signed up for a Nest Developer Account and set off to experiment with the api.

The first thing you need to do is register your client application with Nest.  To do this log into your Nest developer account and fill out some simple information most of which you can change later if you want so don’t worry about getting this too much.  After creating your client application with Nest you will be provided with OAuth settings and urls.  Keep these handy because you are going to need them!

Users of your Nest client application will authenticate with Nest via the OAuth 2.0 specification.  Remember those OAuth settings and urls from earlier?  These are the for the OAuth 2.0 implementation that Nest provides for you.  Nest provides a good authorization overview on its website but let’s break it down a bit further and see it in action.

Authorization

Step 1 – Allow your user to authenticate with their Nest Account

To do this you will need to generate a web request to the following url (found in OAuth settings from earlier): https://home.nest.com/login/oauth2?client_id={your client id}&state=STATE

This is a one time authorization and your user will get a pincode from Nest.  They will need to remember this pincode to get their authorization token (which you will store as a cookie on their device later).

Example pincode response from Nest.

Example pincode response from Nest.

Step 2 – Retrieve authorization token from Nest

Utilizing the pincode that Nest gave us we can make an authorization request and get a permanent authorization token to access the Nest api on behalf of our user.  To do this we make the a web request to the following url:

https://api.home.nest.com/oauth2/access_token?code={pincode}&client_id={your client id}&client_secret={your client secret}&grant_type=authorization_code

By default Nest is blocking cross origin requests so if your language of the month happens to be Javascript (as is mine) then you will need to go about this a different way.  In my case I create a simple WebAPI endpoint to act as a proxy for testing.

[EnableCors(origins: "*", headers: "*", methods: "*")]
        public string Get(string url)
        {
            var data = Convert.FromBase64String(url);
            var decodedString = Encoding.UTF8.GetString(data);

            var request = WebRequest.CreateHttp(decodedString);
            request.Method = "POST";
            request.MediaType = "text/html";

            var response = request.GetResponse();
            var responseStream = response.GetResponseStream();
            var sr = new StreamReader(responseStream, Encoding.UTF8);
            var ret = sr.ReadToEnd();
            response.Close();
            sr.Close();

            return ret;
        }

WebAPI also does not also enable CORS by default so you will need to install the following nuget package: https://www.nuget.org/packages/Microsoft.AspNet.Cors/

After making this request you will receive a JSON object with your access token!

{ access_token: 'c.s90ZxuqbvPXZ...BP6m2xQn', expires_in: '315360000'}

I suggest storing the access token as a cookie so your user does not need to continue authenticating with Nest.

Nest uses Firebase as its data platform.  Accessing the data is simple in several languages as well as a REST endpoint for virtually every other language it does not provide a library for.  Since Nest uses Firebase as its data platform the api calls are actually from the Firebase api but the data model is defined by Nest .  Firebase allows you to sign up for a free account to learn their api incase you don’t want to poke around your Nest data right away.  Firebase is also event driven, meaning that you subscribe data change events so when settings change on your Nest you will be able to respond and do something.

Now that we have an authorization token let’s see how simple it is to read all of the settings from a Nest Thermostat.

function getNestData() {
        var accessToken = $.cookie('nestAccessToken');
        var ref = new Firebase('wss://developer-api.nest.com');
        ref.auth(accessToken);
        ref.on('value', function (snapshot) {
            console.log(snapshot.val());
        });
    }

Of course long term we will want to do some error handling to determine if we are authorized but you get the point.  Firebase returns a JSON object to us in the model defined by Nest.

A response from my Nest!

A response from my Nest!

As you can see it is simple to get started so try it out for yourself!

Share

7 comments for “Beginning with the Nest API

  1. joe
    December 23, 2016 at 3:30 am

    I dont think the PIN the is provided by nest to the user is permanent. It expired in 48 hours. Do you know of a way to auto request one periodically without having the user to enter it?

    • Nick Branstein
      January 3, 2017 at 10:30 am

      No but the token that comes back should be valid for a much longer time – so theoretically you can set the token to expire in a year and you will not need to re-authenticate using a pin (because the oauth token is still valid).

  2. Aashish Mittal
    January 19, 2018 at 7:41 am

    Hi Team,

    I am not able to Install Firebase so unable to proceed further. Please provide some solution for it. I am using VS2012 moreover i need the response of movement in front of camera so above api call can fulfill this need if not than below api should work? As it is returning me not found Json result.
    https://developer-api.nest.com/devices/cameras//is_online?auth=

Leave a Reply

Your email address will not be published. Required fields are marked *