Python Examples

Python Example for findItemsByKeywords

Sample: Basic Call

Retrieves a set of items based on keywords provided.

Task

You want to search Bonanza for items matching the keywords "The King".

Code

Basic Python script to search for items matching "The King":

import requests
import json

url = 'http://api.bonanza.com/api_requests/standard_request'

header = {'X-BONANZLE-API-DEV-NAME' : 'my_dev_name',
        'X-BONANZLE-API-CERT-NAME' : 'my_cert_name'}

request_name = 'findItemsByKeywords'

# create an input dictionary describing a new item
input_dictionary = { 'keywords': 'The King' }

# convert the dictionary to JSON
input_json = json.dumps(input_dictionary)

# concatenate the request name and the input json
payload = request_name + "=" + input_json

# make the request to Bonanza
response = requests.post(url, data=payload, headers=header)

# the json response as a dictionary
response_json = response.json()

# examine the response
if response_json['ack'] == 'Success' and 'findItemsByKeywordsResponse' in response_json:
    for item in response_json['findItemsByKeywordsResponse']['item']:
        print "Title: " + item['title']
        print "Item URL: " + item['viewItemURL']
else:
    # error message in case of bad response from Bonapitit
    print "The request to Bonapitit failed."
    print "Did you forget to fill in the 'X-BONANZLE-API-DEV-NAME'?"

Data

input_json's value (JSON):

{"keywords":"The King"}}

response_json's value (JSON):

{
    "timestamp":"2009-10-31T14:47:13.000Z",
    "version":"1.0",
    "findItemsByKeywordsResponse":{
        "paginationOutput":{
            "totalEntries":2471394,
            "pageNumber":1,
            "entriesPerPage":20
        },
        "item":[
            {
                "primaryCategory":{
                    "categoryName":"Clothing, Shoes amp; Accessories >> Unisex Clothing, Shoes amp; Accs >> Unisex Adult Clothing >> T-Shirts",
                    "categoryId":155193
                },
                "listingInfo":{
                    "price":9.99,
                    "convertedBuyItNowPrice":9.99,
                    "bestOfferEnabled":"true",
                    "listingType":"FixedPrice",
                    "buyItNowPrice":9.99,
                    "startTime":"2009-10-31T00:09:01.000Z",
                    "lastChangeTime":"2009-10-31T00:09:01.000Z"
                },
                "viewItemURL":"http://www.bonanza.com/booths/tshirt_seller_dev/items/CHESS__THE_KING__LOGO_Royal_Blue_T_SHIRT",
                "location":"CA",
                "title":"CHESS \"THE KING\" LOGO Royal Blue T-SHIRT",
                "sellerInfo":{
                    "feedbackRatingStar":"Blue",
                    "membershipLevel":null,
                    "sellerUserName":"T-Shirt Sellin' Deven",
                    "availableForChat":"false",
                    "userPicture":"http://s3.amazonaws.com/bonanzaimages/user_profile_image/afu/user_profile_images/â?¦.jpg",
                    "positiveFeedbackPercent":"100"
                },
                "itemId":7410001,
                "storeInfo":{
                    "storeName":"Deven's T-Shirt Shoppe",
                    "storeDiscount":null,
                    "storeURL":"http://www.bonanza.com/booths/tshirt_seller_dev",
                    "storeHasBonanza":"false",
                    "storeItemCount":6
                },
                "shippingInfo":{
                    "shippingServiceCost":2.99,
                    "shippingType":"Flat",
                    "shipToLocations":"US"
                },
                "sellingStatus":{
                    "convertedCurrentPrice":9.99,
                    "sellingState":"Active",
                    "currentPrice":9.99
                },
                "postalCode":"94536",
                "paymentMethod":["Paypal"],
                "galleryURL":"http://s3.amazonaws.com/bonanzaimages/afu/images/2889/3800/shirt-chess-king.jpg",
                "globalId":"Bonanza",
                "descriptionBrief":"This shirt is only for KINGS!"
            },
            {
                "primaryCategory":{
                    "categoryName":"Home amp; Garden",
                    "categoryId":11700
                },
                "listingInfo":{
                    "price":10.0,
                    "convertedBuyItNowPrice":10.0,
                    "bestOfferEnabled":"true",
                    "listingType":"FixedPrice",
                    "buyItNowPrice":10.0,
                    "startTime":"2009-10-31T00:04:35.000Z",
                    "lastChangeTime":"2009-10-31T00:04:35.000Z"
                },
                "viewItemURL":"http://www.bonanza.com/booths/â?¦",
                "location":"Bolingbrook, IL",
                "title":"Elvisâ?¦",
                "sellerInfo":{
                    "feedbackRatingStar":"Yellow",
                    "membershipLevel":null,
                    "sellerUserName":"â?¦",
                    "availableForChat":"false",
                    "userPicture":"http://s3.amazonaws.com/bonanzaimages/user_profile_image/afu/user_profile_images/â?¦.jpg",
                    "positiveFeedbackPercent":"100"
                },
                "itemId":7920002,
                "storeInfo":{
                    "storeName":"â?¦",
                    "storeDiscount":null,
                    "storeURL":"http://www.bonanza.com/booths/â?¦",
                    "storeHasBonanza":"false",
                    "storeItemCount":1
                },
                "shippingInfo":{
                    "shippingServiceCost":0,
                    "shippingType":"Free",
                    "shipToLocations":"US"
                },
                "sellingStatus":{
                    "convertedCurrentPrice":10.0,
                    "sellingState":"Active",
                    "currentPrice":10.0
                },
                "postalCode":"60446",
                "paymentMethod":["MOCC","Paypal"],
                "galleryURL":"http://s3.amazonaws.com/bonanzaimages/afu/images/â?¦",
                "globalId":"Bonanza",
                "descriptionBrief":"â?¦"
            },
            â?¦
        ]
    },
    "ack":"Success"
}

Python Example for fetchToken

Sample: User Token Fetching

Code

Python script to fetch a token:

import requests

url = 'https://api.bonanza.com/api_requests/secure_request'

header = {'X-BONANZLE-API-DEV-NAME' : 'my_dev_name',
        'X-BONANZLE-API-CERT-NAME' : 'my_cert_name'}

request_name = 'fetchTokenRequest'

# make the request to Bonanza
response = requests.post(url, data=request_name, headers=header)

# the json response as a dictionary
response_json = response.json()

# examine the response
if response_json['ack'] == 'Success' and 'fetchTokenResponse' in response_json:
    token_response = response_json['fetchTokenResponse']
    print "Your token: " + token_response['authToken']
    print "Token expiration time: " + token_response['hardExpirationTime']
    print "Authentication URL: " + token_response['authenticationURL']
else:
    # in case of bad response from Bonapitit
    print "The request to Bonapitit failed"
    print "Did you forget to fill in the 'X-BONANZLE-API-CERT-NAME'?"

Data

response_json's value (JSON [formatted for legibility]):

{
  "ack":"Success",
  "version":"1.0beta",
  "timestamp":"2015-01-14T17:23:15.000Z",
  "fetchTokenResponse":{
    "authToken":"eIJgdkZkMq",
    "hardExpirationTime":"2016-01-14T17:23:15.000Z",
    "authenticationURL":"https://www.bonanza.com/login?apitoken=eIJgdkZkMq"
  }
}

Python Example for getCategories

Sample: Getting Categories

Code

Python script to get information of all children categories of the provided categoryID:

import requests
import json

url = 'http://api.bonanza.com/api_requests/standard_request'

header = {'X-BONANZLE-API-DEV-NAME' : 'my_dev_name',
        'X-BONANZLE-API-CERT-NAME' : 'my_cert_name'}

request_name = 'getCategoriesRequest'

# create an input dictionary searching for 'Baby' category (2984)
input_dictionary = { 'categoryParent': 2984 }

# convert the dictionary to JSON
input_json = json.dumps(input_dictionary)

# concatenate the request name and the input json
payload = request_name + "=" + input_json

# make the request to Bonanza
response = requests.post(url, data=payload, headers=header)

# the json response as a dictionary
response_json = response.json()

# examine the response
if response_json['ack'] == 'Success' and 'getCategoriesResponse' in response_json:
    response = response_json['getCategoriesResponse']

    for category in response['categoryArray']:
        print "Category ID: " + str(category['categoryId'])
        print "Category Name: " + str(category['categoryName'])
else:
  # in case of bad response from Bonapitit
  print "The request to Bonapitit failed."
  print "Did you forget to send categoryParent?"

Data

response_json's value (JSON [formatted for legibility]):

{
  "ack":"Success",
  "version":"1.0beta",
  "timestamp":"2015-01-14T16:47:26.000Z",
  "getCategoriesResponse":{
    "categoryArray":[
      {
        "categoryId":1261,
        "categoryLevel":2,
        "categoryName":"Baby >> Other",
        "leafCategory":"true",
        "categoryBriefName":"Other",
        "traitCount":4
      },
      {
        "categoryId":19068,
        "categoryLevel":2,
        "categoryName":"Baby >> Toys for Baby",
        "leafCategory":"false",
        "categoryBriefName":"Toys for Baby",
        "traitCount":4
      },
      {
        "categoryId":20394,
        "categoryLevel":2,
        "categoryName":"Baby >> Bathing & Grooming",
        "leafCategory":"false",
        "categoryBriefName":"Bathing & Grooming",
        "traitCount":4
      }
    ]
  }
}

Python Example for getOrders

Sample: Getting Orders

Code

Python script to get order information for a seller in a specific time period

import requests
import json

url = 'https://api.bonanza.com/api_requests/secure_request'

header = {'X-BONANZLE-API-DEV-NAME' : 'my_dev_name',
        'X-BONANZLE-API-CERT-NAME' : 'my_cert_name'}

request_name = 'getOrdersRequest'

# create an input hash searching for orders in a time period
input_dictionary = { 
    'requesterCredentials': { 'bonanzleAuthToken': "my_auth_token" },
    'orderRole': 'seller',
    'soldTimeFrom': '2013-01-13',
    'soldTimeTo': '2016-01-13'
    }

# convert the dictionary to JSON
input_json = json.dumps(input_dictionary)

# concatenate the request name and the input json
payload = request_name + "=" + input_json

# make the request to Bonanza
response = requests.post(url, data=payload, headers=header)

# the json response as a dictionary
response_json = response.json()

# examine the response
if response_json['ack'] == 'Success' and 'getOrdersResponse' in response_json:
    response = response_json['getOrdersResponse']

    # print results
    for order_dico in response['orderArray']:
        order = order_dico['order']
        print "Order " + str(order['orderID']) + "------------------"
        print "Buyer Username: " + str(order['buyerUserName'])
        print "Amount Paid: " + str(order['amountPaid'])
        print "Checkout Status: " + str(order['checkoutStatus']['status'])
        print "Created Time: " + str(order['createdTime'])
else:
    # in case of bad response from Bonapitit
    print "The request to Bonapitit failed."

Data

response_json's value (JSON [formatted for legibility]):

{
  "ack":"Success",
  "version":"1.0beta",
  "timestamp":"2015-01-14T16:55:25.000Z",
  "getOrdersResponse":{
    "orderArray":[
      {
        "order":{
          "amountPaid":"104.32",
          "amountSaved":0.0,
          "buyerCheckoutMessage":"",
          "buyerUserID":6157,
          "buyerUserName":"JDoe",
          "checkoutStatus":{
            "status":"Complete"
          },
          "createdTime":"2013-04-25T16:54:25Z",
          "creatingUserRole":"Buyer",
          "itemArray":[
            {
              "item":{
                "itemID":205172,
                "sellerInventoryID":null,
                "sku":null,
                "title":"76 Blank DVD Cases",
                "price":"24.0",
                "quantity":1
              }
            }
          ],
          "orderID":1811,
          "orderStatus":"Shipped",
          "subtotal":24.0,
          "taxAmount":0.0,
          "total":"104.32",
          "transactionArray":{
            "transaction":{
              "buyer":{
                "email":"testy@bonanza.com"
              },
            "providerName":"Checkout by Amazon",
            "providerID":"104-1031316-4215451",
            "finalValueFee":"3.3"
            }
          },
          "paidTime":"2013-04-25T17:08:24Z",
          "shippedTime":"2014-04-28T23:19:08Z",
          "shippingAddress":{
            "addressID":6710,
            "cityName":"SEATTLE",
            "country":"US",
            "countryName":null,
            "name":"Test User",
            "postalCode":"98122-90210",
            "stateOrProvince":"WA",
            "street1":null,
            "street2":null
          },
          "shippingDetails":{
            "insuranceFee":0,
            "amount":"81.52",
            "servicesArray":[],
            "shippingService":"Standard shipping"
          }
        }
      }],
    "hasMoreOrders":"false",
    "paginationResult":{
      "totalNumberOfEntries":2,
      "totalNumberOfPages":1
    },
    "pageNumber":1
  }
}

Python Example for addFixedPriceItem

Sample: Adding an Item

Code

Python script to add an item

import requests
import json

url = 'https://api.bonanza.com/api_requests/secure_request'

header = {'X-BONANZLE-API-DEV-NAME' : 'my_dev_name',
        'X-BONANZLE-API-CERT-NAME' : 'my_cert_name'}

request_name = 'addFixedPriceItemRequest'

# create an input dictionary describing a new item
input_dictionary = { 
  'requesterCredentials': { 'bonanzleAuthToken': "my_auth_token" },
  'item': {
    'title': 'Lightsaber',

    'primaryCategory': {
      'categoryId': '163128'
    },

    'description': 'An elegant weapon, for a more civilized age<br>* SELLER <strong>NOT LIABLE</strong> FOR DISMEMBERMENT *',
    'itemSpecifics': [['condition', 'used'], ['danger', 'extreme']],
    'price': 42,
    'quantity': 3,
    'shippingType': 'Free',

    'pictureDetails': {
      'pictureURL': ['http://images.discountstarwarscostumes.com/products/9284/1-1/luke-skywalker-blue-lightsaber.jpg', 'http://www.rankopedia.com/CandidatePix/29862.gif']
    },

    'variations': [
      {
        'quantity': 2,
        'nameValueList': [
          { 
            'name': 'Colour',
            'value': 'Blue'
          },
          {
            'name': 'Style',
            'value': 'Single'
          }
        ]
      },
      {
        'quantity': 1,
        'nameValueList': [
          { 
            'name': 'Colour',
            'value': 'Red'
          },
          {
            'name': 'Style',
            'value': 'Double'
          },
        ]
      }
    ]
  },
}

# convert the dictionary to JSON
input_json = json.dumps(input_dictionary)

# concatenate the request name and the input json
payload = request_name + "=" + input_json

# make the request to Bonanza
response = requests.post(url, data=payload, headers=header)

# the json response as a dictionary
response_json = response.json()

# check if we got a response back
if response_json['ack'] == 'Success' and 'addFixedPriceItemResponse' in response_json:
    output_fields = response_json['addFixedPriceItemResponse']
    print "Item ID: " + str(output_fields['itemId'])
    print "Category ID: " + str(output_fields['categoryId'])
    print "Selling State: " + output_fields['sellingState']
else:
    # error message in case of bad response from Bonapitit
    print "The request to Bonapitit failed."
    print "Did you forget to fill in the 'X-BONANZLE-API-DEV-NAME'?"

Data

response_json's value (JSON [formatted for legibility] ):

{
        "ack":"Success",
        "version":"1.0beta",
        "timestamp":"2015-01-14T17:05:23.000Z",
        "addFixedPriceItemResponse":{
                "itemId":206013,
                "categoryId":163128,
                "sellingState":"Ready for sale",
                "message":null
        }
}