Backpack API and Perl

25 Jul 2007

A page about using the Backpack API from Perl.

Net::Backpack is now available. Currently it only covers the pages section of the API, but other calls will be included before too long.

And here’s a link to Net::Backpack on CPAN.

Perl Module Example 18 May 2005

Here’s the previous example rewritten to use the Net::Backpack module that I’m working on.

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Net::Backpack;

my $token = 'YOUR-TOKEN-HERE';
my $user  = 'YOUR-USERNAME-HERE';

my $bp = Net::Backpack->new(user  => $user,
                            token => $token);

print Dumper $bp->get_all_pages;

Which is a lot simpler.

Or if you want to get the raw XML and process it yourself you can add the ‘xml => 1’ parameter to the get_all_pages call

print Dumper $bp->get_all_pages(xml => 1);

And here’s the prototype of the Net::Backpack module.

package Net::Backpack;

use strict;
use warnings;
use Carp;
use LWP::UserAgent;
use HTTP::Request;
use XML::Simple;

sub new {
  my $class = shift;
  my %params = @_;

  my $self;
  $self->{token} = $params{token} or croak 'No token';
  $self->{user}  = $params{user}  or croak 'No user';

  $self->{ua} = LWP::UserAgent->new;
  $self->{ua}->default_header('X-POST_DATA_FORMAT' => 'xml');

  return bless $self, $class;
}

sub get_all_pages {
  my $self = shift;
  my %params = @_;

  my $url   = "http://$self->{user}.backpackit.com/ws/pages/all";

  my $req   = HTTP::Request->new(POST => $url);
  $req->content("<request>
  <token>$self->{token}</token>
</request>");

  my $resp = $self->{ua}->request($req);
  my $xml = $resp->content;

  if ($params{xml)) (
    return $xml;
  } else {
    my $data = XMLin($xml);
    return $data;
  }
}

1;

Simple Perl Example 18 May 2005

Calling “list all pages” in Perl. All this proof of concept does is to pull the returned XML into a Perl data structure and dumps it out.

Should be simple enough to change to make alternative calls.

As a demo, this code omits all error checking.

#!/usr/bin/perl

use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use XML::Simple;
use Data::Dumper;

my $token = 'YOUR TOKEN HERE';
my $user  = 'YOUR USERNAME HERE';

my $url   = "http://$user.backpackit.com/ws/pages/all";

my $ua    = LWP::UserAgent->new;
$ua->default_header('X-POST_DATA_FORMAT' => 'xml');

my $req   = HTTP::Request->new(POST => $url);

$req->content("<request>
  <token>$token</token>
</request>");

my $resp = $ua->request($req);
my $xml = $resp->content;

my $data = XMLin($xml);
print Dumper $data;