Last active
December 9, 2019 11:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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'])
.