Click here to Skip to main content
15,867,851 members
Articles / Web Development / ASP.NET
Tip/Trick

Getting Tickets Information from Zendesk API

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
5 Jun 2014CPOL 29.4K   504   3   14
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:

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

Declare the following variables:

C#
/// <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:

C#
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.

C#
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.

C#
/// <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.

C#
/// <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.

C#
/// <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:

Image 1

License

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


Written By
Software Developer
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionError Pin
Maitree Shah12-Aug-21 6:17
Maitree Shah12-Aug-21 6:17 
QuestionThank you!! Pin
rl_lyw13-Feb-18 9:25
rl_lyw13-Feb-18 9:25 
QuestionProject Not Working Pin
Member 1299947221-Sep-17 3:16
Member 1299947221-Sep-17 3:16 
Questionproblem Pin
Member 1162438218-Nov-15 3:26
Member 1162438218-Nov-15 3:26 
AnswerRe: problem Pin
Chamila Nishantha18-Nov-15 16:29
Chamila Nishantha18-Nov-15 16:29 
QuestionRe: problem Pin
Mxolisi Zondi17-Jan-17 3:46
Mxolisi Zondi17-Jan-17 3:46 
SuggestionRe: problem Pin
Mxolisi Zondi17-Jan-17 4:06
Mxolisi Zondi17-Jan-17 4:06 
GeneralRe: problem Pin
a1ace1a5-Aug-19 6:18
a1ace1a5-Aug-19 6:18 
SuggestionNice but why reinventing the wheel? Pin
G. Ber10-Jun-14 5:56
G. Ber10-Jun-14 5:56 
GeneralRe: Nice but why reinventing the wheel? Pin
Chamila Nishantha11-Jun-14 17:01
Chamila Nishantha11-Jun-14 17:01 
AnswerRe: Nice but why reinventing the wheel? Pin
Mxolisi Zondi17-Jan-17 3:48
Mxolisi Zondi17-Jan-17 3:48 
QuestionNice! Pin
Volynsky Alex5-Jun-14 22:37
professionalVolynsky Alex5-Jun-14 22:37 
AnswerRe: Nice! Pin
Chamila Nishantha5-Jun-14 23:01
Chamila Nishantha5-Jun-14 23:01 
QuestionRe: Nice! Pin
Volynsky Alex6-Jun-14 0:23
professionalVolynsky Alex6-Jun-14 0:23 

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

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