API Read Examples

Away

Use the Nest API to listen for changes on structures and devices, so you can take steps to conserve energy when the homeowners are away, notify them that something is amiss (for example, the garage door is open), or activate features to make the home more comfortable and welcoming.

This guide shows how to read data from Nest devices and structures. To learn how to make write calls, see API Write Examples.

Prerequisites

Before making API calls, obtain an access token, as described in Authenticating with OAuth 2.0 and Sample Code for Authorization.

About REST read calls

For REST calls, use GET to read data.

REST read calls are useful is limited scenarios, such as the following use cases:

  • Ad-hoc one-off calls
  • Proof-of-concept labs
  • Troubleshooting
  • Apps that poll approximately every minute
  • Refresh button implementations

REST read calls are not useful for continuous real-time or streaming scenarios.

Bearer authentication

We recommend compliance with the OAuth standard, which offers increased security by using "Bearer" authentication to transmit the access token. Calls with client credentials in the URL are not recommended.

The "Content-Type" header directs the server to use JSON.

The "Authorization" header provides API access.

Examples

In the following examples, replace YOUR_TOKEN_HERE with your specific access token, such as "c.twC2q...".

Read structures and devices

To read all the structure and device data (base level), use the root-level URL. For more granular responses, modify the URL as needed.

Curl
curl -v --location-trusted \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -X GET "https://developer-api.nest.com/"
Curl multiplex
curl -v --location-trusted \
  -H "Accept: text/event-stream" \
  -H "Authorization: Bearer LIST_OF_ACCESS_TOKENS" \
  -X GET "https://developer-api.nest.com/multiplex"
Go
package main

import (
    "errors"
    "fmt"
    "io/ioutil"
    "net/http"
)

const token = "YOUR_TOKEN_HERE" // Update with your token

func main() {
    url := "https://developer-api.nest.com/"
    req, _ := http.NewRequest(http.MethodGet, url, nil)

    req.Header.Add(
        "Authorization",
        fmt.Sprintf("Bearer %s", token),
    )

    customClient := http.Client {
        CheckRedirect: func(redirRequest *http.Request, via []*http.Request) error {
            // Go's http.DefaultClient does not forward headers when a redirect 3xx
            // response is received. Thus, the header (which in this case contains the
            // Authorization token) needs to be passed forward to the redirect
            // destinations.
            redirRequest.Header = req.Header

            // Go's http.DefaultClient allows 10 redirects before returning an
            // an error. We have mimicked this default behavior.
            if len(via) >= 10 {
                return errors.New("stopped after 10 redirects")
            }
            return nil
        },
    }

    response, _ := customClient.Do(req)

    if response.StatusCode != 200 {
        panic(fmt.Sprintf(
            "Expected a 200 status code; got a %d",
            response.StatusCode,
        ))
    }

    defer response.Body.Close()
    body, _ := ioutil.ReadAll(response.Body)
    fmt.Println(string(body))

}
Node.js
"use strict"

var request = require('request');

var token = "YOUR_TOKEN_HERE"; // Update with your token

var url = "https://developer-api.nest.com";

var options = {
    "method": "GET",
    "path": "/",
    "headers": {
       "Authorization": "Bearer " + token
    },
    "followRedirect": true
};

var req = request(url, options, function(err, resp, data) {
    console.log('response code: ' + resp.statusCode);
    if (err) {
        console.log('Error: ' + err.message);
    }
    console.log("data: " + data);
});

req.end();

To use the Node.js code example, install the request module (https://www.npmjs.com/package/request).

npm install request
Python 2
import hashlib
import json
import os
import requests

url = "https://developer-api.nest.com/"

token = "YOUR_TOKEN_HERE" # Update with your token

headers = {'Authorization': 'Bearer {0}'.format(token), 'Content-Type': 'application/json'}

response = requests.get(url, headers=headers, allow_redirects=False)
if response.status_code == 307:
    response = requests.get(response.headers['Location'], headers=headers, allow_redirects=False)

print(response.text)
Python 3
import http.client
from urllib.parse import urlparse

token = "YOUR_TOKEN_HERE" # Update with your token

conn = http.client.HTTPSConnection("developer-api.nest.com")
headers = {'authorization': "Bearer {0}".format(token)}
conn.request("GET", "/", headers=headers)
response = conn.getresponse()

if response.status == 307:
    redirectLocation = urlparse(response.getheader("location"))
    conn = http.client.HTTPSConnection(redirectLocation.netloc)
    conn.request("GET", "/", headers=headers)
    response = conn.getresponse()
    if response.status != 200:
        raise Exception("Redirect with non 200 response")

data = response.read()
print(data.decode("utf-8"))
Java
import java.io.IOException;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Authenticator;
import okhttp3.Route;

public class ReadNest {

    public static void main(String[] args) throws IOException {
        String auth = "Bearer YOUR_TOKEN_HERE"; // Update with your token

        OkHttpClient client = new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
          @Override public Request authenticate(Route route, Response response) throws IOException {
            return response.request().newBuilder()
                .header("Authorization", auth)
                .build();
          }
        })
        .followRedirects(true)
        .followSslRedirects(true)
        .build();

        Request request = new Request.Builder()
        .url("https://developer-api.nest.com")
        .get()
        .addHeader("content-type", "application/json; charset=UTF-8")
        .addHeader("authorization", auth)
        .build();

        try {
            System.out.println("Begin request:  ");
            Response response = client.newCall(request).execute();
            System.out.println(response.body().string());
            System.out.println("End request");
            System.out.println();
            Thread.sleep(2 * 1000);
        } catch (InterruptedException e) {
                e.printStackTrace();
        }
   }
}

To use the Java code example:

1. Download the latest okhttp and okio Jar files at http://square.github.io/okhttp/.

2. Construct your code.

3. Compile and run the program with the following class-path settings.

javac -cp .:okhttp-3.5.0.jar:okio-1.11.0.jar ReadNest.java
java -cp .:okhttp-3.5.0.jar:okio-1.11.0.jar ReadNest

Using Postman to test the API

The above Curl call can easily be replicated in Postman.

PUT header to write

Use the Code link in Postman to translate a call into different languages as a starting point for further development.