Skip to content

Instantly share code, notes, and snippets.

@kgonzago
Created February 10, 2020 12:51
Show Gist options
  • Save kgonzago/6d503d0623e0e1c3c028eef930fa9570 to your computer and use it in GitHub Desktop.
Save kgonzago/6d503d0623e0e1c3c028eef930fa9570 to your computer and use it in GitHub Desktop.
Get tickets for February 2020 using Zendesk Search API
import time
import requests
import json
import os
import csv
from urllib.parse import urlencode
def GetUserJSON(exec_url, session):
'''
Retrieves JSON representation of
user based on input user id
'''
response = session.get(exec_url)
if response.status_code != 200:
return None
user_data = response.json()
return user_data['user']
def CreateTicketsList(exec_url, session):
'''
Execute input URL and return a list
of tickets
'''
ret_list = []
while exec_url:
response = session.get(exec_url)
if response.status_code == 429:
print('Rate limited! Please wait.')
time.sleep(int(response.headers['retry-after']))
continue
if response.status_code != 200:
print('Error with status code {}'.format(response.status_code))
exit()
data = response.json()
if data['count'] == 0:
break
ret_list.extend(data['results']) # Append all tickets to list
exec_url = data['next_page'] # Check if we have more tickets - pagination
return ret_list
# Parameters
credentials = 'username', 'password' # username and password for zendesk
column_headers = ['Type', 'Date Created', 'Date Modified', 'Name', 'Subject', 'Issue Description'] # Column headers for CSV file
column_list = ['type', 'created_at', 'created_at', 'subject', 'description'] # Fields to query with
zendesk_url = 'https://reavencrest-test.zendesk.com' # Zendesk url for your organization
tickets_url = '/api/v2/tickets.json' # Rest endpoint to retrieve tickets
search_url = '/api/v2/search.json?' # Rest endpoint to search tickets
users_url = '/api/v2/users/{0}.json' # Rest endpoint for getting specific users
file_name = 'tickets.csv' # File name to print tickets to
org_id = 370322681513 # Your Zendesk organization id
get_tickets_url = zendesk_url + tickets_url
query_tickets_url = zendesk_url + search_url
do_get_tickets = False # Set to False to get all tickets. Set to True to query for tickets in February
# Get all tickets in February 2020 and sort in ascending order
params = {
'query': 'type:ticket created>=2020-02-01 created<=2020-02-29',
'sort_by': 'created_at', # sort field
'sort_order': 'asc' # from oldest to newest
}
query_tickets_url += urlencode(params)
# Set appropriate url to execute
execute_url = get_tickets_url if do_get_tickets else query_tickets_url
# Create session with proper credentials
session = requests.Session()
session.auth = credentials
# Delete existing file
if os.path.exists(file_name):
os.remove(file_name)
# Holds tickets
ticket_list = CreateTicketsList(execute_url, session)
if len(tickets_url) > 0:
# Write to file
with open(file_name, 'w') as ticket_file:
# Open a csv writer
file_writer = csv.writer(ticket_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
# Write column headers
file_writer.writerow(column_headers)
# Iterate through tickets
for ticket in ticket_list:
val_list = []
for column in column_list:
val_list.append(str(ticket[column]))
exec_url = zendesk_url + users_url.format(ticket['requester_id'])
user_json = GetUserJSON(exec_url, session)
valid_name = str(user_json['name']) if user_json != None else 'None'
val_list.insert(3, valid_name)
file_writer.writerow(val_list)
else:
print('Unable to retrieve tickets')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment