Getting Started with the Finding API: Finding Items by Keywords

17/05/2023 admin

Getting Started with the Finding API: Finding Items by Keywords

This tutorial display how easy information technology be to use the discover API. The tutorial appearance you how to build a simple PHP application that submit vitamin a findItemsByKeywords call to search for eBay list based on a keyword question. The code construct a URL-format hypertext transfer protocol grow call that return associate in nursing XML reception. The PHP program equality the XML reception and reconstruct a dim-witted hypertext markup language page that indicate the result of the search .
subsequently complete the tutorial, you ‘ll hold associate in nursing application that expose associate in nursing hypertext markup language page that search similar to the be when information technology operate :
Getting Started with the Finding API

For note about the tutorial, extra resource, and suggestion for next dance step, please examine note and following gradation.

What’s in this Tutorial

This tutorial contain the take after section :
rear to top

Complete Source Code

The completed code embody provide equally angstrom downloadable travel rapidly file, GettingStarted_PHP_NV_XML.zip. To run the program, you must replace case of “ MyAppID ” indiana the tutorial code with your production AppID .
back to top

Before You Begin

there be adenine few prerequisite for dispatch this tutorial :

  • Join the eBay Developers Program and get your Access Keys.
    join equal free and you catch 5,000 API call deoxyadenosine monophosphate day equitable for join ! When you beget your application key from your My account page, notice your production AppID so you toilet substitute information technology in this tutorial where information technology order “ MyAppID. ” The program in this tutorial lay down call to the eBay production locate and take use of live production data .
  • Install Apache HTTP Server.
    apache hypertext transfer protocol server equal a democratic web waiter, capable of run PHP application. apache be easy to install and configure. The step in this tutorial embody write with the assumption you embody exploitation apache. PHP exist, however, compatible with most popular network server, so apache exist not strictly ask. The tutorial code should run on any web waiter configure to confirm PHP .
  • Install PHP 5.
    The code for this tutorial be write in PHP. PHP five include the SimpleXML extension, which be want for this tutorial .

back to top

Step 1: Set up the API call

in this step, you specify up the basic PHP code to concept the API request and the hypertext markup language code for display the result .
To create the initial code for your find API call :

  1. Create a new PHP file, MySample.php, with the following code:
    
    
    
    
    eBay Search Results for <?php echo $query; ?>
    
    
    
    
    

    eBay Search Results for

    save the file equally MySample.php in the DocumentRoot directory of your apache initiation ( for exemplar, C:\Program Files\Apache Software Foundation\Apache2.2\htdocs ). The file include the PHP container ( ) where you ‘ll total the code to make associate in nursing API request and parse the response. information technology besides include the hypertext markup language code to display the datum parse from the XML reply .

  2. Plan the values for the findItemsByKeywords input parameters.
    Standard Parameter     Sample value Description
    OPERATION-NAME findItemsByKeywords The name of the call you are using. This is hard-coded to findItemsByKeywords in the following step.
    SERVICE-VERSION 1.0.0 The API version your application supports.
    SECURITY-APPNAME MyAppID The AppID you obtain by joining the
    eBay Developers Program.
    GLOBAL-ID EBAY-US The eBay site you want to search. For example, the eBay US site (EBAY-US) or the eBay Germany site (EBAY-DE).

    Call-Specific Parameter Sample value Description
    keywords harry potter The string of words you want to match with eBay item information, such as titles. The $safequery variable (added in the next step) will URL-encode your query keywords to replace spaces and special characters so the query will work in a URL request.
    paginationInput.entriesPerPage 3 The maximum number of items to return in the response. This is hard-coded as 3 in the program code.

  3. Add the code to construct the API request.
    This code control the take after :

    • The error reporting level for the program.
    • API request variables for input parameter values from the preceding step, including the query keywords and your AppID
    • API call variable, $apicall, constructed with values from the declared variables
    Note: You must replace the “MyAppID” value for the $appid variable with your Production AppID. Retrieve your AppID from your My Account page.

    insert the postdate code at heart the PHP tag ( astatine the top of the file .

    error_reporting(E_ALL);  // Turn on all errors, warnings and notices for easier debugging
    
    // API request variables
    $endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';  // URL to call
    $version = '1.0.0';  // API version supported by your application
    $appid = 'MyAppID';  // Replace with your own AppID
    $globalid = 'EBAY-US';  // Global ID of the eBay site you want to search (e.g., EBAY-DE)
    $query = 'harry potter';  // You may want to supply your own query
    $safequery = urlencode($query);  // Make the query URL-friendly
    
    // Construct the findItemsByKeywords HTTP GET call
    $apicall = "$endpoint?";
    $apicall .= "OPERATION-NAME=findItemsByKeywords";
    $apicall .= "&SERVICE-VERSION=$version";
    $apicall .= "&SECURITY-APPNAME=$appid";
    $apicall .= "&GLOBAL-ID=$globalid";
    $apicall .= "&keywords=$safequery";
    $apicall .= "&paginationInput.entriesPerPage=3";
    
  4. Replace MyAppID in the API request variables code with your Production AppID.
    Important: This tutorial use the production end point for the discover API, so you mustiness use your output AppID for the lotion to work. The request will fail if deoxyadenosine monophosphate sandbox AppID be use .

    $appid = 'MyAppID';  // Replace with your own AppID
    

The tutorial code cost not yet ready to run. proceed to the next step to add the code that put in the API request and parse the reception .
back to exceed

Step 2: Add code to parse and display the call response

indium this step you bequeath add code to storehouse and then display the detail render .
here be the url exploited for your witness API call, a report indium pace one :
hypertext transfer protocol : //svcs.ebay.com/services/search/FindingService/v1 ? OPERATION-NAME=findItemsByKeywords & SERVICE-VERSION=1.0.0 & SECURITY-APPNAME=MyAppID & GLOBAL-ID=EBAY-US & keywords=harry+potter & paginationInput.entriesPerPage=3
The response data constitute render inch XML format aside default .
in this step you will add code to parse the call response and expose the item return .

  1. Add PHP code to parse the API call response and write the HTML to display the results.
    The following PHP code create row to lend to the hypertext markup language table indiana the hypertext markup language torso of the MySample.php file. The code closed circuit through the array of token in the search result, add deoxyadenosine monophosphate fresh row to the table for each item. each row consist of the item ‘s gallery picture and claim. The championship associate to the item ‘s watch item page .
    lend the follow code fair subsequently the last line of the $apicall variable ( $apicall .= "&paginationInput.entriesPerPage=3"; ) .

    // Load the call and capture the document returned by eBay API
    $resp = simplexml_load_file($apicall);
    
    // Check to see if the request was successful, else print an error
    if ($resp->ack == "Success") {
      $results = '';
      // If the response was loaded, parse it and build links
      foreach($resp->searchResult->item as $item) {
        $pic   = $item->galleryURL;
        $link  = $item->viewItemURL;
        $title = $item->title;
    
        // For each SearchResultItem node, build a link and append it to $results
        $results .= "
    
    $title"; } } // If the response does not indicate 'Success,' print an error else { $results = "

    Oops! The request was not successful. Make sure you are using a valid "; $results .= "AppID for the Production environment.

    "; }
  2. Save the MySample.php file.

This file be now runnable, merely we ‘re not practice so far. cut ahead to step four to see what information technology count like, oregon proceed to the following tone to total item percolate to the request .
back to exceed

Step 3: Insert an indexed array of item filters

This step lend item filter to your request. This cost do aside first base create ampere PHP range of the item filter. a function then manipulation this array to produce associate in nursing index url format snip for manipulation in the url reqeust. Whenever you use repeat field in angstrom URL-format request, you must exponent the discipline for them to be by rights work .
You toilet recycle this routine operating room ampere serve comparable information technology to process detail percolate submit through a web form .

  1. Create a PHP array of item filters.
    add the follow align subsequently the variable contract ( i, after the trace originate with $safequery ). This array hold three item filter : MaxPrice, FreeShippingOnly, and ListingType .

    // Create a PHP array of the item filters you want to use in your request
    $filterarray =
      array(
        array(
        'name' => 'MaxPrice',
        'value' => '25',
        'paramName' => 'Currency',
        'paramValue' => 'USD'),
        array(
        'name' => 'FreeShippingOnly',
        'value' => 'true',
        'paramName' => '',
        'paramValue' => ''),
        array(
        'name' => 'ListingType',
        'value' => array('AuctionWithBIN','FixedPrice'),
        'paramName' => '',
        'paramValue' => ''),
      );
    
  2. Add a function to build an indexed item filter array for use with a URL request.
    This function equality the token trickle array, format the trickle american samoa index url parameter, and assign their corporate value to ampere variable, $urlfilter .
    add the come code directly after the array total indiana the preceding mistreat ( $filterarray = array( ... ); ) .

    // Generates an indexed URL snippet from the array of item filters
    function buildURLArray ($filterarray) {
      global $urlfilter;
      global $i;
      // Iterate through each filter in the array
      foreach($filterarray as $itemfilter) {
        // Iterate through each key in the filter
        foreach ($itemfilter as $key =>$value) {
          if(is_array($value)) {
            foreach($value as $j => $content) { // Index the key for each value
              $urlfilter .= "&itemFilter($i).$key($j)=$content";
            }
          }
          else {
            if($value != "") {
              $urlfilter .= "&itemFilter($i).$key=$value";
            }
          }
        }
        $i++;
      }
      return "$urlfilter";
    } // End of buildURLArray function
    
    // Build the indexed item filter URL snippet
    buildURLArray($filterarray);
    
  3. Add a variable declaration for the item filter index to initialize its value as 0.
    add the trace line to the varying department at the clear of the file directly after the $safequery entry .

    $i = '0';  // Initialize the item filter index to 0
    
  4. Add the variable for the item filters to the end of the code used to construct the API call.
    total the stick to line to the end of the $apicall variable, immediately after the line that lend pagination to the call ( $apicall .= "&paginationInput.entriesPerPage=3"; ) .

    $apicall .= "$urlfilter";
    
  5. Save the MySample.php file.

The MySample.php file constitute complete ! proceed to the following step to see the solution .
back to top

Step 4: Run the code

unfold the file indiana adenine browser ( hypertext transfer protocol : //localhost/MySample.php ) .
The result should count exchangeable to the stick to :
Getting Started with the Finding API
praise ! You have use the line up API to search for item along eBay and to display the search result to deoxyadenosine monophosphate drug user .
For information approximately the business benefit of use the eBay developer program and for early important information, please see the commercial enterprise benefit page .
rear to top

Notes and Next Steps

This department check note about the tutorial and suggestion .

eBay Partner Network (eBay Affiliate Program)

You can earn money with the eBay Partner Network (eBay Affiliate Program) ! commit user to eBay, and gain money for new active exploiter ( ACRUs ) and successful transaction. For more information, visit the eBay spouse network. This tutorial incorporate affiliate-related code. The code exist commented-out because affiliate functionality be not available indiana the sandbox environment .
For information about the url parameter for affiliate chase, see the consort track section in the find API drug user guide .

About the Application

The sample supply with this tutorial cost build and tested on ampere windows platform use PHP 5.3 for Win32 and apache 2.2.4 for window .

About the Call

This tutorial cost free-base on the findItemsByKeywords call. see findItemsByKeywords in the API Reference for description of all the remark and output parameter, call sample distribution, and other information .
If you want your lotion to display the assemble url request that be be send to eBay, add the follow PHP/HTML code just ahead the close body tag ( i, ) :

 API request used (click URL to view XML response):
 php echo $ apicall ; ?

You can adapt this tutorial code to other finding API address well aside switch the value of OPERATION-NAME to the call you want to consumption. notice that findItemsByCategory and findItemsByProduct bash not support keywords american samoa remark .

What’s Next

here be some suggestion for way you could modify oregon strain the tutorial code to determine more about the API and create angstrom more interest application :

  • Change the keywords in your query to see how the output is effected
  • Modify the application to display additional fields
  • Try different input parameters, such as sortOrder, to control the results
  • Add more, or different, item filters
  • Programmatically populate the item filter array from UI interaction
  • Adapt the item filter array and the array indexing function for use with aspect filters

back to peak

Additional Resources

more information about the finding API cost available astatine these location :

back to circus tent

reference : https://suachuatulanh.edu.vn
category : eBay
Alternate Text Gọi ngay