doodlesalot
11/1/2017 - 7:05 PM

Get count of tags within a Zendesk search Python script

Get count of tags within a Zendesk search Python script

import json

def jprint(to_print, indent=4, sort_keys=True):
    print(json.dumps(to_print, indent=indent, sort_keys=sort_keys))
zendesk_user = 'zendesk_user@example.com'
zendesk_token = 'your_zendesk_token'
import requests
from secrets import zendesk_user, zendesk_token
from util import jprint
import urllib.parse
import sys
from collections import Counter


USER = zendesk_user + '/token'
PWD = zendesk_token
#You can test your search in Zendesk directly
SEARCH = 'created>=2017-10-01 created<2017-11-01 type:ticket'
ZENDESK_SUBDOMAIN = 'your-zd-subdomain-here'

search_url_encoded = urllib.parse.quote(SEARCH)
url = 'https://%s.zendesk.com/api/v2/search.json?query=%s' % (ZENDESK_SUBDOMAIN, search_url_encoded)

def get_all_pages(url):
    results = []

    while url:
        #print url
        response = requests.get(url, auth=(USER, PWD))
        data = response.json()

        results.extend(data["results"])
        url = data["next_page"]
        #url = None #If you're playing with data and want a faster feedback loop, uncomment this line to get just 100 tickets

    return results

results = get_all_pages(url)
tags = []

for r in results:
    tags.extend(r["tags"])

tag_counts =  Counter(tags)



jprint(len(results))


jprint(tag_counts)

##Before you begin

Lazy update for Python 3.x. You'll need to have the requests package installed.

##Setup

  1. Setup 3 files that correspond to the 3 Python files in this gist within a single folder.
  2. In secrets.py, add your Zendesk account email and token. To get a token, from within Zendesk, go to Settings > API > Token Access (Enabled), then click the plus sign near "Active API Tokens".
  3. In query_zendesk_search_stats_tags.py, change SEARCH and ZENDESK_SUBDOMAIN for your needs.
  4. To run, type python query_zendesk_search_stats_tags.py from the command line and press enter. It will take about 2.5 seconds for each 100 tickets in the search. E.g. 811 tickets took ~22 seconds.