Page tree
Skip to end of metadata
Go to start of metadata

C# .Net 4.5.1 Example

The following code example shows how to connect to our API and performs the following actions:

  1. Calls api/4.5/ping/noauth to show a non-authenticated GET request
  2. Calls api/4.5/ping/auth to show an unauthorised GET request
  3. Calls api/token to retrieve the authorisation token (POST)
  4. Calls api/4.5/ping/auth with the token to show an authorised GET request
  5. Calls api/4.5/ping/exampleerror with the same token to show re-using the token and how an error will look (POST)

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Web;
using System.Net.Http.Headers;

namespace Api.Test
{
    class Program
    {
        public class PingExampleErrorRequest
        {
            public override string ToString()
            {
                return JsonConvert.SerializeObject(this);
            }

            [JsonProperty(PropertyName = "Number")]
            public string Number { get; set; }

            [JsonProperty(PropertyName = "Description")]
            public string Description { get; set; }

        }

        public class LoginTokenResult
        {
            public override string ToString()
            {
                return AccessToken;
            }

            [JsonProperty(PropertyName = "access_token")]
            public string AccessToken { get; set; }

            [JsonProperty(PropertyName = "error")]
            public string Error { get; set; }

            [JsonProperty(PropertyName = "error_description")]
            public string ErrorDescription { get; set; }

        }

        static void Main(string[] args)
        {
            try
            {
                var username = "test";
                var password = "test";


                using(var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://betaservices.p.vu/api/");

                    //call api with no auth
                    Console.WriteLine("Calling API: ping/noauth");
                    HttpResponseMessage resp = client.GetAsync("4.5/ping/noauth").Result;
                    resp.EnsureSuccessStatusCode();
                    var now = resp.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(now);

                    Console.WriteLine("");
                    Console.WriteLine("Calling API: ping/auth (without access token)");
                    try
                    {
                        resp = client.GetAsync("4.5/ping/auth").Result;
                        resp.EnsureSuccessStatusCode();
                        now = resp.Content.ReadAsStringAsync().Result;
                        Console.WriteLine(now);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    //get token
                    Console.WriteLine("");
                    Console.WriteLine("Calling API: token");
                    resp = client.PostAsync("token", new StringContent(
                        string.Format("grant_type=password&username={0}&password={1}", HttpUtility.UrlEncode(username), HttpUtility.UrlEncode(password)), 
                        Encoding.UTF8, 
                        "application/x-www-form-urlencoded")).Result;
                    
                    //This method throws an exception if the HTTP response status is an error code.
                    resp.EnsureSuccessStatusCode();
                    var tokenJson = resp.Content.ReadAsStringAsync().Result;
                    var token = JsonConvert.DeserializeObject<LoginTokenResult>(tokenJson);

                    Console.WriteLine("Access Token:" + token.AccessToken);
                    Console.WriteLine("Error:" + token.Error);
                    Console.WriteLine("Error Desc:" + token.ErrorDescription);

                    Console.WriteLine("");
                    Console.WriteLine("Calling API: ping/auth (with access token)");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
                    resp = client.GetAsync("4.5/ping/auth").Result;
                    resp.EnsureSuccessStatusCode();
                    now = resp.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(now);

                    Console.WriteLine("");
                    Console.WriteLine("Calling API: ping/exampleerror (with access token)");
                    var postData = new PingExampleErrorRequest { Number = "API-UN-12345", Description = "Test error" };
                    resp = client.PostAsJsonAsync("4.5/ping/exampleerror", postData).Result;
                    resp.EnsureSuccessStatusCode();
                    now = resp.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(now);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR");
                var exWorking = ex;
                do
                {
                    Console.WriteLine(exWorking.Message);
                    exWorking = exWorking.InnerException;
                } while (exWorking != null);
            }
            Console.WriteLine("Press any key to quit");
            Console.ReadKey(true);
        }
    }
}

Results

Tips

 

The user account specified in the example code is a dummy account, please use your own ClickSuper provided credentials.

 

  • No labels