JSON API » Sample clients » C#

// This is a sample client for the Enswitch JSON API.
// It is released into the public domain.
// It comes with absolutely no warranty, and is not supported.

using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;

namespace CallAPI
{
    class Program
    {
        private static String base = "http://enswitch.example.com/api/json/";
        private static String function = "access/list";
        private static String username = "testuser";
        private static String password = "testpass";
        
        static void Main(string[] args)
        {
            try
            {
                WebClient wc = new WebClient();
                Stream result_stream = wc.OpenRead(String.Format("{0}{1}?auth_username={2};auth_password={3}", base, function, username, password));
                StreamReader reader = new StreamReader(result_stream);
                String api_result_string = new StreamReader(result_stream).ReadToEnd();
                dynamic api_result = JsonConvert.DeserializeObject(api_result_string);

                // Check for error responses
                foreach (var response in api_result["responses"]) {
                    if (response["code"] >= 400)
                    {
                        Console.WriteLine("Error: {0} {1}", response["code"], response["message"]);
                        Environment.Exit(response["code"]);
                    }
                }

                // List out accounts
                foreach (var data in api_result["data"])
                {
                    Console.WriteLine("Remote access account ID:{0} name:{1}", data["id"], data["name"]);
                }
            }

            catch (WebException ex)
            {
                Console.WriteLine("API fetch failed: {0}", ex.Message);
            }
            catch (JsonException ex)
            {
                Console.WriteLine("Error parsing result: {0}", ex.Message);
            }
        } 
    }
}