Skip to content

Instantly share code, notes, and snippets.

@chucknado
Last active December 9, 2019 11:32
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save chucknado/95a1e9c771e46bb94e9b to your computer and use it in GitHub Desktop.
Save chucknado/95a1e9c771e46bb94e9b to your computer and use it in GitHub Desktop.
A Python script for the REST API tutorial, "Backing up your knowledge base," at https://help.zendesk.com/hc/en-us/articles/229136947
import os
import datetime
import csv
import requests
credentials = 'your_zendesk_email', 'your_zendesk_password'
zendesk = 'https://your_subdomain.zendesk.com'
language = 'some_locale'
date = datetime.date.today()
backup_path = os.path.join(str(date), language)
if not os.path.exists(backup_path):
os.makedirs(backup_path)
log = []
endpoint = zendesk + '/api/v2/help_center/{locale}/articles.json'.format(locale=language.lower())
while endpoint:
response = requests.get(endpoint, auth=credentials)
if response.status_code != 200:
print('Failed to retrieve articles with error {}'.format(response.status_code))
exit()
data = response.json()
for article in data['articles']:
if article['body'] is None:
continue
title = '<h1>' + article['title'] + '</h1>'
filename = '{id}.html'.format(id=article['id'])
with open(os.path.join(backup_path, filename), mode='w', encoding='utf-8') as f:
f.write(title + '\n' + article['body'])
print('{id} copied!'.format(id=article['id']))
log.append((filename, article['title'], article['author_id']))
endpoint = data['next_page']
with open(os.path.join(backup_path, '_log.csv'), mode='wt', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow( ('File', 'Title', 'Author ID') )
for article in log:
writer.writerow(article)
@jham1
Copy link

jham1 commented May 6, 2016

Partially works for me. Everything is smooth until I hit this error:

Traceback (most recent call last): File "make_backup.py", line 34, in <module> f.write(title + '\n' + article['body']) TypeError: Can't convert 'NoneType' object to str implicitly

My assumption is that I have a saved draft with no article body and this is causing the NoneType error. Any thoughts?

@biancarosa
Copy link

I had to check if article['body'] was None, and if it was, I just logged the article id, skipping the write file part.

@chucknado
Copy link
Author

chucknado commented Jan 4, 2017

Thanks @biancarosa and @jham1. I added a check for an empty article body in the for article in data['articles'] loop. The script broke when it tried to concatenate a string type with a 'NoneType' in (title + '\n' + article['body']).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment