Last active
February 22, 2016 21:41
-
-
Save chucknado/49f7d0e71a6fc61210af to your computer and use it in GitHub Desktop.
A Perl script for the REST API tutorial, "Backing up your knowledge base with Perl", at https://support.zendesk.com/hc/en-us/articles/204395003
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
use strict; | |
use warnings; | |
use MIME::Base64; | |
use LWP::UserAgent; | |
use JSON; | |
use Time::Piece; | |
use File::Spec::Functions; | |
use File::Path 'make_path'; | |
my $credentials = encode_base64('your_email_address:your_password'); | |
my $ua = LWP::UserAgent->new(ssl_opts =>{ verify_hostname => 0 }); | |
my $zendesk = 'your_zendesk_url'; | |
my $language = 'the_locale'; | |
my $time = Time::Piece->new; | |
my $date = $time->date; | |
my $backup_path = catdir($date, $language); | |
make_path($backup_path); | |
my $log = "File\tTitle\tAuthor ID\n"; | |
my $endpoint = $zendesk . '/api/v2/help_center/' . lc($language) . '/articles.json'; | |
while ($endpoint) { | |
my $response = $ua->get($endpoint, 'Authorization' => "Basic $credentials"); | |
die 'Failed to retrieve articles with error ' . $response->code . ' ' . $response->message | |
unless ($response->is_success); | |
my $data = decode_json($response->content); | |
my @articles = @{ $data->{'articles'} }; | |
foreach my $article ( @articles ) { | |
open my $fh, '>:encoding(UTF-8)', "$backup_path/$article->{'id'}.html" | |
or die "Could not open file $!"; | |
print $fh "<h1>$article->{'title'}</h1>\n$article->{'body'}"; | |
close $fh; | |
print "$article->{'id'} copied!\n"; | |
$log .= "$article->{'id'}.html\t$article->{'title'}\t$article->{'author_id'}\n"; | |
} | |
if (defined $data->{'next_page'}) { | |
$endpoint = $data->{'next_page'}; | |
} else { | |
$endpoint = ''; | |
} | |
} | |
open my $log_fh, '>:encoding(UTF-8)', "$backup_path/_log.txt" | |
or die "Could not open file $!"; | |
print $log_fh $log; | |
close $log_fh; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment