Code Examples

To help developers along the way, we have created code examples of how you can use the Toon®  API yourself. These code examples can be found for some of the most popular programming languages. These examples deal with the steps from authenticating the user, to making the call to check the current temperature for the Toon display. These examples can be used as easy stepping stones to start building your own application.

Once you have the code example for your preferred programming language implemented and executed in your local environment you can go over to the Swagger IO page to start expanding your application and implementing all the API calls as you like.

The code examples are kept as simple as possible and the only adjustment you will have to make is inserting the credentials for your personal Toon Developer account.

Java

Below is the Java code that you can copy and paste to make the calls to the API in your own project. This will be able to retrieve the temperature of a Toon display. 

Create a new class ToonAPIClient that contains all the code from ‘Toon API Client’. Then use the code from ‘Method calling’ to execute the code and display the temperature.

Please note that this example uses the javax.json.Json library which is included in Java 8 EE.

Method Calling
ToonAPIClient client = new ToonAPIClient();
String accessToken = client.GetAccessToken();

String agreementId = client.GetAgreementId(accessToken);
client.PostAgreementId(accessToken, agreementId);

double temp = client.GetTemperatureFromStatus(accessToken);
System.out.println("Current temperature: " + temp + "°C");
ToonAPIClient
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.bind.DatatypeConverter;

public class ToonAPIClient
{
 private String Username = "";
    private String Password = "";
    private String API_Key = "";
    private String API_Secret = "";
    
    private URL APIManagerBaseAddress;
    private URL APIBaseAddress;
 
    public ToonAPIClient() throws MalformedURLException
    {
    APIManagerBaseAddress = new URL("https://api.toonapi.com");
        APIBaseAddress = new URL(APIManagerBaseAddress + "/toon/api/v1");
    }
    
 public String GetAccessToken() throws IOException
 {
 if (Username == "" || Password == "") {
            throw new IOException("Credentials not provided");
        }
 
 if (API_Key == "" || API_Secret == "") {
            throw new IOException("API details not provided");
        }
 
 String appendedKeyAndSecret = API_Key + ":" + API_Secret;
        String authorizationHeader = "Basic " + Base64Encode(appendedKeyAndSecret);
        
        String urlParameters = "grant_type=password&username=" + Username + "&password=" + Password;
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
 
        URL tokenEndpoint = new URL(APIManagerBaseAddress + "/token");
    HttpsURLConnection urlConnection = (HttpsURLConnection) tokenEndpoint.openConnection();
    
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Authorization", authorizationHeader);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    
    try(OutputStream out = urlConnection.getOutputStream())
    {
     out.write(postData);
     
     String inputStr;
     String response = "";
     try(InputStream in = urlConnection.getInputStream()) {
     try(BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {
     while ((inputStr = streamReader.readLine()) != null) {
     response += inputStr.toString();
     }
     }
     }
     JsonObject object = StringToJson(response);
     String accessToken = object.getString("access_token");
     return accessToken;
    }
 }
 
 public String GetAgreementId(String accessToken) throws IOException
 {
 URL tokenEndpoint = new URL(APIBaseAddress + "/agreements");
    HttpsURLConnection urlConnection = (HttpsURLConnection) tokenEndpoint.openConnection();
    
    urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);
    
    String inputStr;
    String response = "";
    try(InputStream in = urlConnection.getInputStream()) {
     try(BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {
     while ((inputStr = streamReader.readLine()) != null) {
     response += inputStr.toString();
     }
     }
    }
    JsonArray agreements = StringToJsonArray(response);
    JsonObject firstAgreement = agreements.getJsonObject(0);
    String agreementId = firstAgreement.getString("agreementId");
    
    return agreementId;
 }
 
 public void PostAgreementId(String accessToken, String agreementId) throws Exception
 {
 JsonObject agreement = Json.createObjectBuilder()
 .add("agreementId", agreementId).build();
 byte[] postData = agreement.toString().getBytes(StandardCharsets.UTF_8);
 
 URL tokenEndpoint = new URL(APIBaseAddress + "/agreements");
    HttpsURLConnection urlConnection = (HttpsURLConnection) tokenEndpoint.openConnection();
    
    urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    
    try(OutputStream out = urlConnection.getOutputStream())
    {
     out.write(postData);
     urlConnection.connect();
     int code = urlConnection.getResponseCode();
     if(code != 200)
     throw new Exception("Post agreement unsuccessful");
    }
 }
 
 public double GetTemperatureFromStatus(String accessToken) throws IOException
 {
 URL tokenEndpoint = new URL(APIBaseAddress + "/status");
    HttpsURLConnection urlConnection = (HttpsURLConnection) tokenEndpoint.openConnection();
    
    urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);
    
    String inputStr;
    String response = "";
    try(InputStream in = urlConnection.getInputStream()) {
     try(BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {
     while ((inputStr = streamReader.readLine()) != null) {
     response += inputStr.toString();
     }
     }
    }
    JsonObject statusInfo = StringToJson(response);
    JsonObject thermostatInfo = statusInfo.getJsonObject("thermostatInfo");
    int currentTemp = thermostatInfo.getInt("currentTemp");
    
    double formattedTemp = currentTemp / 100;
    return formattedTemp;
  }
 
 public static JsonObject StringToJson(String input)
 {
 try(JsonReader jsonReader = Json.createReader(new StringReader(input)))
 {
 JsonObject obj = jsonReader.readObject();
 return obj;
 }
 }
 
 public static JsonArray StringToJsonArray(String input)
 {
 try(JsonReader jsonReader = Json.createReader(new StringReader(input)))
 {
 JsonArray obj = jsonReader.readArray();
 return obj;
 }
 }
 
 public static String Base64Encode(String plainText) throws UnsupportedEncodingException
 {
 byte[] plainTextBytes = plainText.getBytes("UTF-8");
 String encoded = DatatypeConverter.printBase64Binary(plainTextBytes);
 return encoded; 
 }
}
C#

Below is the C# code that you can copy and paste to make the calls to the API in your own project. This will be able to retrieve the temperature of a Toon display. 

Create a new class ToonAPIClient that contains all the code from ‘Toon API Client’. Then use the code from ‘Method calling’ to execute the code and display the temperature.

Please note that this example uses the Newtonsoft.Json NuGet package.

Method Calling
var client = new ToonAPIClient();
var accessToken = client.GetAccessToken();

var agreementId = client.GetAgreementId(accessToken);
client.PostAgreementId(accessToken, agreementId);

var temp = client.GetTemperatureFromStatus(accessToken);
Console.WriteLine("Current temperature: {0}°C", temp);
ToonAPIClient
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace ToonAPIExample
{
    public class ToonAPIClient
    {
        private string Username = "";
        private string Password = "";
        private string API_Key = "";
        private string API_Secret = "";
        private Uri APIManagerBaseAddress;
        private Uri APIBaseAddress;
        public ToonAPIClient()
        {
            APIManagerBaseAddress = new Uri("https://api.toonapi.com");
            APIBaseAddress = new Uri(APIManagerBaseAddress + "toon/api/v1/");
        }
        public string GetAccessToken()
        {
            using (HttpClient client = new HttpClient())
            {       
                if(string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
                    throw new Exception("Credentials not provided");
                if (string.IsNullOrEmpty(API_Key) || string.IsNullOrEmpty(API_Secret))
                    throw new Exception("API details not provided");
                var appendedKeyAndSecret = string.Format("{0}:{1}", API_Key, API_Secret);
                var authorizationHeader = Base64Encode(appendedKeyAndSecret);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorizationHeader);
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("grant_type", "password"),
                    new KeyValuePair<string, string>("username", Username),
                    new KeyValuePair<string, string>("password", Password),
                });
                client.BaseAddress = APIManagerBaseAddress;
                var result = client.PostAsync("token", content).Result;
                string stringResult = result.Content.ReadAsStringAsync().Result;
                var jsonResult = JsonConvert.DeserializeObject<JObject>(stringResult);
                var accessToken = jsonResult.GetValue("access_token").ToString();
                return accessToken;
            }
        }
        public string GetAgreementId(string accessToken)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = APIBaseAddress;
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                var result = client.GetAsync("agreements").Result;
                string stringResult = result.Content.ReadAsStringAsync().Result;
                var jsonResult = JsonConvert.DeserializeObject<JObject[]>(stringResult);
                var firstAgreement = jsonResult[0];
                var agreementId = firstAgreement.GetValue("agreementId").ToString();
                return agreementId;
            }
        }
        public void PostAgreementId(string accessToken, string agreementId)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = APIBaseAddress;
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                var anonObj = new { agreementId = agreementId };
                var stringJson = ConvertToStringContent(anonObj);
                client.PostAsync("agreements", stringJson).Wait();
            }
        }
        public void SetTemperature(string accessToken, int temp)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = APIBaseAddress;
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                var anonObj = new { value = (temp * 100), scale = "CELSIUS" };
                var stringJson = ConvertToStringContent(anonObj);
                var result = client.PutAsync("temperature", stringJson).Result;
                string stringResult = result.Content.ReadAsStringAsync().Result;
            }
        }
        public double GetTemperatureFromStatus(string accessToken)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = APIBaseAddress;
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                var result = client.GetAsync("status").Result;
                string stringResult = result.Content.ReadAsStringAsync().Result;
                var jsonResult = JsonConvert.DeserializeObject<JObject>(stringResult);
                var jsonObj = jsonResult.GetValue("thermostatInfo");
                var currentTemp = jsonObj.ToObject<JObject>().GetValue("currentTemp").ToString();
                var formattedTemp = double.Parse(currentTemp) / 100;
                return formattedTemp;
            }
        }
        public static StringContent ConvertToStringContent(object anonObj)
        {
            var jsonObj = JsonConvert.SerializeObject(anonObj);
            return new StringContent(jsonObj, Encoding.UTF8, "application/json");
        }
        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            return Convert.ToBase64String(plainTextBytes);
        }
    }
}