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 -L -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 device_id.

Curl
curl -L -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))

}
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'}

initial_response = requests.put(url, headers=headers, data=payload, allow_redirects=False)
if initial_response.status_code == 307:
    initial_response = requests.put(initial_response.headers['Location'], headers=headers, data=payload, allow_redirects=False)

print(initial_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:
    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("Redirect with non 200 response", 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/.

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 NestWrite.java
java -cp .:okhttp-3.5.0.jar:okio-1.11.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 -L -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.

curl -L -X PUT \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d "{"label": "Kate's Room"}" \
  "https://developer-api.nest.com/devices/thermostat/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 -L -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.