API Write Examples

Thermostat

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.

In this guide you'll learn how to use the PUT command to write data to Nest devices and structures. To learn how to make read calls, see API Read Examples.

Check out these code samples and learn to write data to the Nest Learning Thermostat and Nest Cam.

Prerequisites

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

About REST write calls

For REST calls, use PUT or PATCH to write data.

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...".

Set the away state for a structure

To change the away state of a structure to "home", write the away field using this format: "{"away": "home"}", where "away" is the name of the field, and "home" is the new state.

To write to a structure, we'll add the /structures object and structure_id to the URL root path. Note that strings are formatted with "quotation marks".

curl --location-trusted -X PUT \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{"away": "home"}' \
  "https://developer-api.nest.com/structures/structure_id"

Change the temperature scale (C/F) on a thermostat

In this example, we'll force the temperature scale to display degrees Fahrenheit. When you're building your product, you would read the temperature scale first, and then decide if you want to change it with a write call.

To make the call, specify the field and value you want to update: "{"temperature_scale": "F"}", and change the root path to include /devices/thermostats and the thermostat device_id.

Curl
curl --location-trusted -X PUT \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{"temperature_scale": "F"}' \
  "https://developer-api.nest.com/devices/thermostats/device_id"
Go
package main

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

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

func main() {

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

    payload := strings.NewReader("{\"temperature_scale\": \"F\"}")

    req, _ := http.NewRequest("PUT", url, payload)

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

    customClient := http.Client{
        CheckRedirect: func(redirRequest *http.Request, via []*http.Request) error {
            redirRequest.Header = req.Header
            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(response)
    fmt.Println(string(body))

}
Node.js
"use strict"

const request = require('request');

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

/* Update with your token and thermostat device ID below */
var path = "/devices/thermostats/device_id";
var token = "YOUR_TOKEN_HERE";

var options = {
    "method": "PUT",
    "url": url + path,
    "body": JSON.stringify({"temperature_scale": "F"}),
    "headers": {
        "Authorization": "Bearer " + token,
        "Content-Type": "application/json"
    },
    "followRedirect": true,
    "removeRefererHeader": false
};

request(options, function(err, resp, data) {
    if (resp.statusCode == 307) { // indicates a redirect is needed
        options.url = resp.headers.location;
        request(options, function(err, resp, data) {
            console.log('response code: ' + resp.statusCode);
            if (err) console.log('Error: ' + err.message);
            console.log("data: " + data);
        });
    }
});

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/devices/thermostats/device_id"

token = "YOUR_TOKEN_HERE" # Update with your token

payload = "{\"temperature_scale\": \"F\"}"

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

response = requests.put(url, headers=headers, data=payload, allow_redirects=False)
if response.status_code == 307: # indicates a redirect is needed
    response = requests.put(response.headers['Location'], headers=headers, data=payload, allow_redirects=False)

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

token = "YOUR_TOKEN_HERE" # Update with your token

payload = "{\"temperature_scale\": \"F\"}"

url = "/devices/thermostats/device_id"

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

if response.status == 307: # indicates a redirect is needed
    redirectLocation = urlparse(response.getheader("location"))
    conn = http.client.HTTPSConnection(redirectLocation.netloc)
    conn.request("PUT", url, payload, headers)
    response = conn.getresponse()
    if response.status != 200:
        raise Exception("Response failed: ", response.reason)

data = response.read()
print(data.decode("utf-8"))
Java
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class NestWrite {

    public Request makeRequest(String url, String value) {
        MediaType mediaType = MediaType.parse("application/octet-stream");
        RequestBody body = RequestBody.create(mediaType, "{\"temperature_scale\": \"F\"}\"");
        String auth = "Bearer YOUR_TOKEN_HERE"; // Update with your token
        Request request = new Request.Builder()
        .url(url)
        .put(body)
        .addHeader("authorization", auth)
        .build();
        return request;
    }

    public static void main(String[] args) throws IOException
    {
        OkHttpClient client = new OkHttpClient();
        NestWrite postman = new NestWrite();

        String url = "https://developer-api.nest.com/devices/thermostats/device_id";
        String value = "{\"away\": \"home\"}";
        Request request = postman.makeRequest(url, value);
        Response response = client.newCall(request).execute();
        //System.out.println(response.toString());

        // Use the new URL in case of temporary redirect
        if(response.isRedirect()){
            String newUrl = response.header("Location");
            request = postman.makeRequest(newUrl, value);
            response = client.newCall(request).execute();
        }
        System.out.println(response.body().string());
    }
}

To use the Java code example:

1. Download the latest okhttp and okio Jar files at http://square.github.io/okhttp/. Additionally, download the Kotlin stdlib file at https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib if your version of okhttp depends on it.

2. Construct your code.

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

Substitute your library version numbers in the javac and java commands below:
javac -cp .:okhttp-<ver>.jar:okio-<ver>.jar NestWrite.java
java -cp .:okhttp-<ver>.jar:okio-<ver>.jar:kotlin-stdlib-<ver>.jar NestWrite

For instance, if you have the following versions 3.11.0, 2.1.0, and 1.3.0, your commands would look like this:
javac -cp .:okhttp-3.11.0.jar:okio-2.1.0.jar NestWrite.java
java -cp .:okhttp-3.11.0.jar:okio-2.1.0.jar:kotlin-stdlib-1.3.0.jar NestWrite

Change the target temperature on a thermostat

After you change the temperature scale to degrees Fahrenheit, you can set the target temperature. Use the same process as previous examples, and specify the field/value to update, and change the root path. Note that "strings" and numbers are formatted differently.

curl --location-trusted -X PUT \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{"target_temperature_f": 70}' \
  "https://developer-api.nest.com/devices/thermostats/device_id"

Set a customized label on a thermostat

You can also change the thermostat label to give it a customized nickname. To include a single quote in the name, you can use the unicode character \u0027.

curl --location-trusted -X PUT \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{"label": "Kate\u0027s Room"}' \
  "https://developer-api.nest.com/devices/thermostats/device_id"

Set the streaming status on a camera

In this example, we change the root path to reflect the device you want to modify, /devices/cameras/device_id, and set the camera streaming state to ON.

curl --location-trusted -X PUT \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{"is_streaming": true}' \
  "https://developer-api.nest.com/devices/cameras/device_id"

Using Postman to test the API

The above Curl calls can easily be replicated in Postman. The steps below changes the target temperature on a thermostat such as in the Curl example above.

PUT header to write
PUT body to write

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