Thermostat data request succeeds in Postman but .NET HttpWebRequest returns 401


#1

First let me say web development isn’t my strong point. I want to write a Windows console program, later to become a Windows service, to periodically poll Nest thermostat data for my own home monitoring. I’ve registered and obtained an authorization token. I can query data from my thermostat when I use Postman. But when I try to use the same GET, with the same auth token, in my little C# program I receive a 401 error. I’ve spent the better part of a day researching, reading Nest developer information, and trying different options, with no success.

Any ideas what I’m missing or doing wrong? Here’s the C# snipet with the device ID and auth token obfuscated.

    string url = "https://developer-api.nest.com/devices/thermostats/my_device_id";
    string accessToken =  my_auth_token";
    
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "GET";
    request.ContentType = "application/json";

    string authorization = $"Bearer {my_auth_token}";
    request.Headers.Add("Authorization", authorization);

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    var encoding = ASCIIEncoding.ASCII;
    using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
    {
        string responseText = reader.ReadToEnd();
    }
    response.Close();

#2

Disregard my question. I solved the problem using the advice posted for a similar question:

Adding the authorization token as a parameter in the URL, with the name “auth” eliminated the 401 error. I am now reading thermostat information.


#3

Thanks for the update on this and glad it is working. We don’t have a .Net sample, but you may want to try request.PreAuthenticate = true if you want to try it again as an Authorization header.