Click here to Skip to main content
Click here to Skip to main content

Getting Tickets Information from Zendesk API

, 5 Jun 2014
Rate this:
Please Sign up or sign in to vote.
Communicating with Zendesk API

Introduction

This tip shows how to connect to Zendesk and fetch tickets information through the API.

Using the Code

Since API responses are based on JSON format, you will need Newtonsoft and RestSharp libraries. Simply install from Nuget and refer to the following namespaces:

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using RestSharp;  

Declare the following variables:

/// <summary>
/// Zend desk username
/// </summary>
private static string _Username = "<UserName>";

/// <summary>
/// Zendesk password
/// </summary>
private static string _Password = "<Password>";

/// <summary>
/// Zendesk URI
/// </summary>
private static string requestUri = "https://<YourcompnayName>.zendesk.com/";

On button click:

    protected void btnLoadtickets_Click(object sender, EventArgs e)
        {
            gvTaskList.DataSource = GetZenDeskJobList();
            gvTaskList.DataBind();
        }

GetZenDeskJobList() method communicates with Zendesk API. Here we are using while loop to fetch records since JSON response is not on continues format.

   public static List<ZenDeskJob> GetZenDeskJobList()
        {
            string username = _Username;
            string password = _Password;

            JObject userInfo;

            List<ZenDeskJob> zenDeskJobs = new List<ZenDeskJob>();
            var client = new RestClient(requestUri);
            client.AddDefaultHeader("Accept", "application/json");
            client.Authenticator = new HttpBasicAuthenticator(username, password);
            string currentResource = "/api/v2/tickets.json";            

            Dictionary<string, string> currentUserList = new Dictionary<string, string>();

            currentUserList = CreateUserList();

            do
            {
                var request = new RestRequest(currentResource, Method.GET);

                IRestResponse response = client.Execute(request);
                var content = response.Content;

                userInfo = JObject.Parse(content);

                foreach (var user in userInfo)
                {
                    if (user.Key == "tickets")
                    {
                        foreach (var x in user.Value)
                        {
                            AddTicketInfoToList(x, zenDeskJobs, currentUserList);
                        }
                    }
                    if (user.Key == "next_page")
                    {
                        if (user.Value.ToString() != string.Empty)
                        {
                            currentResource = user.Value.ToString().Replace(requestUri, string.Empty);

                        }
                        else
                        {
                            currentResource = string.Empty;
                        }
                    }
                }  
            }
            while (currentResource != string.Empty);

            return zenDeskJobs;

        }

AddTicketInfoToList() method reads the JSON response and query required output.

        /// <summary>
        /// Add ticket information to list
        /// </summary>
        /// <param name="jtoken">Jtoken</param>
        /// <param name="zenDeskJobs">List of zendesk jobs</param>
        /// <param name="userList">List of users</param>
        private static void AddTicketInfoToList(JToken jtoken, List<ZenDeskJob> zenDeskJobs, Dictionary<string, string> userList)
        {
            ZenDeskJob singleTicket = new ZenDeskJob();

            JObject jObject = JObject.Parse(jtoken.ToString());

            var y = jtoken["custom_fields"];

            JObject joType = y.Children<JObject>().FirstOrDefault
            (o => o["id"] != null && 
            o["id"].ToString() == "20256231");
            JObject joSite = y.Children<JObject>().FirstOrDefault
            (o => o["id"] != null && 
            o["id"].ToString() == "20598381");
            JObject joTimeSpent = y.Children<JObject>().FirstOrDefault
            (o => o["id"] != null && 
            o["id"].ToString() == "20285557");

            var legend = joType.GetValue("value");
            var timeSpent = joTimeSpent.GetValue("value");

            if (legend != null && legend.ToString() == "charge_hourly_rate" 
            && jtoken["status"] != null 
            && jtoken["status"].ToString() == "solved")
            {
                singleTicket.ZenDeskId = jObject["id"] != null ? 
                jObject["id"].ToString() : string.Empty;

                string currentUserID = jObject["assignee_id"].ToString();
                string assigneeName = string.Empty;

                userList.TryGetValue(currentUserID, out assigneeName);

                singleTicket.Assignee = assigneeName;

                singleTicket.TaskName = jObject["subject"] != null ? 
                jObject["subject"].ToString() : string.Empty;
               
                singleTicket.TotalTimeSpent = timeSpent != null ? timeSpent.ToString() : string.Empty; ;

                singleTicket.URL = "https://yourcompany.zendesk.com/agent/#/tickets/" + 
                (jObject["id"] != null ? jObject["id"].ToString() : string.Empty);

                zenDeskJobs.Add(singleTicket); 
            }
        }

Here, we need to mention user name which ticket is assigned.

        /// <summary>
        /// Creating zendesk user list
        /// </summary>
        /// <returns>concurrent dictionary</returns>
        private static Dictionary<string, string> CreateUserList()
        {
            string username = _Username;
            string password = _Password;

            JObject userInfo;

            Dictionary<string, string> userList = new Dictionary<string, string>();
            var client = new RestClient(requestUri);
            client.AddDefaultHeader("Accept", "application/json");
            client.Authenticator = new HttpBasicAuthenticator(username, password);
            string currentResource = "/api/v2/users.json";

            do
            {
                var request = new RestRequest(currentResource, Method.GET);

                IRestResponse response = client.Execute(request);
                var content = response.Content;

                userInfo = JObject.Parse(content);

                foreach (var user in userInfo)
                {
                    if (user.Key == "users")
                    {
                        foreach (var x in user.Value)
                        {
                            userList.Add(x["id"].ToString(), 
                            x["name"] != null ? x["name"].ToString() : string.Empty);
                        }
                    }
                    if (user.Key == "next_page")
                    {
                        if (user.Value.ToString() != string.Empty)
                        {
                            currentResource = user.Value.ToString().Replace(requestUri, string.Empty);

                        }
                        else
                        {
                            currentResource = string.Empty;
                        }
                    }
                } 
            }
            while (currentResource != string.Empty);

            return userList;

        }

We need another simple class to hold basic zendesk records to bind the grid.

        /// <summary>
        /// Zendesk job business entities
        /// </summary>
        public class ZenDeskJob
        {
            /// <summary>
            /// Gets or sets ZenDeskId
            /// </summary>
            public string ZenDeskId
            {
                get;
                set;
            }               

            /// <summary>
            /// Gets or sets task names
            /// </summary>
            public string TaskName
            {
                get;
                set;
            }

            /// <summary>
            /// Gets or sts total time spent
            /// </summary>
            public string TotalTimeSpent
            {
                get;
                set;
            }

            /// <summary>
            /// Gets or sets assignee
            /// </summary>
            public string Assignee
            {
                get;
                set;
            }

            /// <summary>
            /// Gets or sets ticket url
            /// </summary>
            public string URL
            {
                get;
                set;
            }
        }

Once the Load Ticket button is pressed, conditioned zendesk tickets will be displayed on the grid. Output will look like below:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Chamila Ranasinghe
Software Developer
Sri Lanka Sri Lanka
No Biography provided

Comments and Discussions

 
SuggestionNice but why reinventing the wheel? PinmemberG. Ber10-Jun-14 5:56 
GeneralRe: Nice but why reinventing the wheel? PinmemberChamila Ranasinghe11-Jun-14 17:01 
QuestionNice! PinpremiumVolynsky Alex5-Jun-14 22:37 
AnswerRe: Nice! PinmemberChamila Ranasinghe5-Jun-14 23:01 
QuestionRe: Nice! PinpremiumVolynsky Alex6-Jun-14 0:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 6 Jun 2014
Article Copyright 2014 by Chamila Ranasinghe
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid