8.1 Hacks #82-100

eBay is more than just a web site. It's a platform upon which you can build your own applications and with which you can extend your business.

The eBay API (Application Programming Interface) is a set of functions you can integrate with your applications to communicate directly with eBay. Use the API to retrieve details about an auction, perform searches, list a seller's current items, and even create new auction listings. Think of the API as a "back door" of sorts, a way for developers to interact with the eBay engine and auction database without using the standard web interface.

The possibilities of such a system are limitless. Businesses can use the eBay API to link their inventory and sales databases with auctions, cutting out most of the labor that would otherwise be involved in selling large numbers of items. Developers can use the API to construct auction management applications for themselves, their companies, or even for commercial sale. And, of course, individual buyers and sellers on eBay can use the API to do a little friendly hacking, as described throughout the rest of this chapter.

8.1.1 How the eBay API Works

The underlying process of placing a call to the API is conceptually quite simple. First, your program sends an XML string to eBay with the name of the API call and any additional required fields. Here's an example XML request for the GetSearchResults function:

<?xml version='1.0' encoding='iso-8859-1'?>
<request>
  <RequestUserId>my_user_id</RequestUserId>
  <RequestPassword>my_password</RequestPassword>
  <ErrorLevel>1</ErrorLevel>
  <DetailLevel>0</DetailLevel>
  <Verb>GetSearchResults</Verb>
  <SiteId>0</SiteId>
  <Query>![CDATA[*abbey road*]]</Query>
</request>

eBay then responds with more XML, from which your application extracts the desired data. The components of the input and output XML will vary with the particular function and the needs of the application, but the overall methodology is the same regardless of the API call being used.

Every single XML request sent to eBay must contain three developer-specific keys, DevID, AppID, and CertID, all of which are provided to you when you join eBay's Developers Program.

8.1.2 Getting Started

Before you can start using the eBay API, you'll need to sign up at developer.ebay.com. There are four different license types (or "tiers"):

  • Individual. This is the free license designed for individual developers. It includes full access to all API calls, but limits usage to only 50 calls per day. The only tangible cost is Certification, as described in [Hack #82].

    Developers using the Individual license have no access to developer technical support (though they can access developer forums), nor can they use Platform Notifications (see [Hack #93]) or sell their programs commercially.

  • Basic. The lowest commercial tier, Basic includes 30,000 calls per month (significantly more than the 50 allotted to Individual developers), with a nominal charge for additional calls. But it also has an annual fee and a higher certification cost, all offset by the ability to create commercial applications (like auction management tools).

  • Professional. The Professional tier is similar to the Basic tier, but with a more expensive annual membership fee, less expensive API usage fees, and more free technical support incidents.

  • Enterprise. The highest commercial tier, Enterprise differs from the Basic and Professional tiers only in the fees and number of free technical support incidents.

Once you've signed up, you can log in and download the eBay API SDK (Software Development Kit).

Although the SDK comes with documentation, the online API Technical Documentation at developer.ebay.com/DevZone/docs/API_Doc/ is the best source for technical information about the API.

8.1.3 Using the Scripts in This Chapter

All of the example scripts in this chapter are written in Perl. Not only is Perl code concise and extremely easy to read, but Perl interpreters are freely available for nearly every computing platform on Earth.

Every script in this chapter relies on the following two scripts. Make sure all your scripts are stored in the same directory. As with all the scripts in this book, you can download them from www.ebayhacks.com/.

  • ebay.pl

    This script contains the common code used in all scripts in this chapter, including the aptly named call_api function.

    #!/usr/bin/perl
    use LWP::UserAgent;
    use HTTP::Request;
    use HTTP::Headers;
    use XML::Simple;
    require 'config.pl';
    
    sub call_api {
      my ($arg) = @_;
      return undef unless $arg->{Verb};
      $arg->{RequestUserId} = $user_id unless defined $arg->{RequestUserId};
      $arg->{RequestPassword} = $password
                                     unless defined $arg->{RequestPassword};
      $arg->{DetailLevel} = "0" unless defined $arg->{DetailLevel};
      $arg->{ErrorLevel} = "1" unless defined $arg->{ErrorLevel};
    
      my $ua   = LWP::UserAgent->new;
      my $head = HTTP::Headers->new
           ('X-EBAY-API-COMPATIBILITY-LEVEL' => $compat_level,
            'X-EBAY-API-SESSION-CERTIFICATE' => "$dev_id;$app_id;$cert_id",
                       'X-EBAY-API-DEV-NAME' => $dev_id,
                       'X-EBAY-API-APP-NAME' => $app_id,
                      'X-EBAY-API-CERT-NAME' => $cert_id,
                      'X-EBAY-API-CALL-NAME' => $arg->{Verb},
                         'X-EBAY-API-SITEID' => $site_id,
                   'X-EBAY-API-DETAIL-LEVEL' => $arg->{DetailLevel}
      );
    
      my $body = XMLout($arg,
                    keeproot => 1,
                     keyattr => undef,
                      noattr => 1,
                    rootname => 'request',
                     xmldecl => 1);
      print STDERR "calling: $body" if $DEBUG;
      my $req = HTTP::Request->new("POST", $api_url, $head, $body);
      my $rsp = $ua->request($req);
      print STDERR "response: $rsp->content" if $DEBUG;
      return undef if !$rsp->is_success;
      return XMLin($rsp->content,
                      forcearray => [qw/Error Item FeedbackDetailItem/],
                         keyattr => undef);
    }
    
    sub print_error {
      my ($xml) = @_;
      foreach (@{$xml->{Errors}{Error}}) {
        print "$_->{Severity}: $_->{LongMessage}\n";
      }
    }
    
    sub formatdate {
      ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($_[0]);
      $year = $year + 1900;
      $mon = $mon + 1;
      return sprintf("%0.4d-%0.2d-%0.2d %0.2d:%0.2d:%0.2d",
                                          $year,$mon,$mday,$hour,$min,$sec);
    }
    
    return true;
  • config.pl

    Next, the config.pl script is used to store personal information such as the developer keys eBay sends you, your username and password, and other variables used throughout this chapter.

    #!/usr/bin/perl
    $api_url      = 'https://temp-sandbox.ebay.com/ws/api.dll';
    $itemurl      = "http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=";
    $compat_level = 309;
    $site_id      = 0; # US
    $DEBUG        = o;
    
    $dev_id       = 'your_DevID';
    $app_id       = 'your_AppID';
    $cert_id      = 'your_CertID';
    $user_id      = 'your_ebay_user_id';
    $password     = 'your_ebay_password';
    $selleremail  = "your_email_address";
    $localdir     = "a_path_on_your_hard_disk";
    
    return true;

Make sure to fill in all the "your" fields in config.pl with your own information. eBay will provide the DevID, AppID, and CertID keys when you join the eBay Developers Program. If you're outside the U.S., change $site_id accordingly. See [Hack #82] for more information on the Compatibility Level ($compat_level). Finally, the two URL variables shouldn't have to be changed.

Nearly everything in Perl (and the eBay API, for that matter) is case sensitive. Always mind your upper- and lowercase when working with the scripts in this chapter.

Special thanks to Todd Larason, without whose help this chapter would not have been possible.