Ruby Examples
- add_fixed_price_item example
- fetch_token example
- find_items_by_keywords example
- get_categories example
- get_orders example
- set_notification_preferences_example
Ruby Example for addFixedPriceItem
Sample: Adding an Item
Code
Ruby script to add an item
require 'rubygems' require 'json' # Hash.to_json(), JSON.parse() require 'net/http' # Net::HTTP#post() require 'cgi' # CGI.escapeHTML() header = {'X-BONANZLE-API-DEV-NAME' => 'my_dev_name', 'X-BONANZLE-API-CERT-NAME' => 'my_cert_name'} request_name = 'addFixedPriceItemRequest' # create an input hash describing a new item input_hash = { 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 hash to JSON input_json = input_hash.to_json # open a connection to Bonanza's API and send the request response = Net::HTTP.new('api.bonanza.com').post( '/api_requests/secure_request', "#{request_name}=#{input_json}", header ) # get response data back as JSON response_json = response.body # convert response data back to a hash response_hash = JSON.parse(response_json) # check if we got a response back if response_hash['ack'] == 'Success' && response_hash.has_key?('addFixedPriceItemResponse') response = response_hash['addFixedPriceItemResponse'] puts "Item ID: #{response['itemId']}" puts "Category ID: #{response['categoryId']}" puts "Selling State: #{response['sellingState']}" else # helpful error message in case of bad response from Bonapitit puts "The request to Bonapitit failed.<br/>" puts "Did you forget to fill in the 'X-BONANZLE-API-DEV-NAME'?<br/>" puts CGI.escapeHTML(response_hash.to_yaml) end
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 } }
Ruby Example for fetchToken
Sample: User Token Fetching
Code
Ruby script to fetch a token:
require 'rubygems' require 'json' # Hash.to_json(), JSON.parse() require 'net/http' # Net::HTTP#post() require 'cgi' # CGI.escapeHTML() header = {'X-BONANZLE-API-DEV-NAME' => 'my_dev_name', 'X-BONANZLE-API-CERT-NAME' => 'my_cert_id'} request_name = 'fetchTokenRequest' # open a connection to Bonanza's API and send the request response = Net::HTTP.new('api.bonanza.com').post( '/api_requests/secure_request', request_name, header ) # get response data back as JSON response_json = response.body # convert response data back to a hash response_hash = JSON.parse(response_json) # check if we got a response back if response_hash['ack'] == 'Success' && response_hash.has_key?('fetchTokenResponse') response = response_hash['fetchTokenResponse'] puts "Your token: #{response['authToken']}" puts "Token expiration time: #{response['hardExpirationTime']}" puts "Authentication URL: #{response['authenticationURL']}" else # helpful error message in case of bad response from Bonapitit puts "The request to Bonapitit failed.<br/>" puts "Did you forget to fill in the 'X-BONANZLE-API-CERT-NAME'?<br/>" puts CGI.escapeHTML(response_hash.to_yaml) end
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" } }
Ruby 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 Ruby script to search for items matching "The King":
require 'rubygems' require 'json' # Hash#to_json(), JSON.parse() require 'net/http' # Net::HTTP#post() require 'cgi' # CGI.escapeHTML() # create an input hash searching for "The King" basic_input_hash = { 'keywords' => 'The King' } # convert it to JSON basic_input_json = basic_input_hash.to_json # open a connection to Bonanza's API and send the request basic_response = Net::HTTP.new("api.bonanza.com").post( '/api_requests/standard_request', "findItemsByKeywords=#{basic_input_json}", {'X-BONANZLE-API-DEV-NAME' => 'elvis_collector_dev'} ) # get the response data back as JSON basic_response_json = basic_response.body # convert the response data back to a hash basic_response_hash = JSON.parse(basic_response_json) # check if we got a response back if basic_response_hash['ack'] == 'Success' && basic_response_hash.has_key?('findItemsByKeywordsResponse') # output a link to each item basic_response_hash['findItemsByKeywordsResponse']['item'].each do |item| item_url = item['viewItemURL'] item_name = CGI.escapeHTML(item['title']) puts %[<a href="#{item_url}">#{item_name}</a><br/>] end else # helpful error message in the case of a bad response from Bonapitit puts "The request to Bonapitit failed.<br/>" puts "Did you forget to fill in the 'X-BONANZLE-API-DEV-NAME'?<br/>" puts CGI.escapeHTML(basic_response_hash.to_yaml) end
Data
basic_input_json's value (JSON):
{"itemFilter":{"keywords":"The King"}}
basic_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":"https://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":"https://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":"https://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":"https://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" }
basic_response_hash's each loop output (HTML, formatted for readability):
<a href="https://www.bonanza.com/booths/tshirt_seller_dev/items/CHESS__THE_KING__LOGO_Royal_Blue_T_SHIRT"> CHESS "THE KING" LOGO Royal Blue T-SHIRT </a> <a href="https://www.bonanza.com/booths/â?¦"> Elvisâ?¦ </a>
Sample: Paginated Results
Retrieves a page of items based on keywords provided and the current page number.
This example's script can either be run from the command-line via:
ruby find_items_by_keywords_pagination.rb «p=2»
or in a simple Ruby web framework (e.g. in [http://www.sinatrarb.com/ Sinatra], although this will require a few quick modifications) via:
http://localhost:4567/find_items_by_keywords_pagination«?p=2»
Task
You want to search Bonanza for items matching the keywords "The King" and show 50 pages of results, each with 30 items on it (and links to jump from page to page).
Code
Basic Ruby keyword search script from the previous example, with pagination added:
require 'rubygems' require 'json' # Hash#to_json(), JSON.parse() require 'net/http' # Net::HTTP#post() require 'cgi' # CGI.escapeHTML() require 'rack' # Rack::Request # define our valid page range and current page number page_range = 1..50 # find the "p" parameter if it was specified, or default to the first page (1) page_number = if defined?(env) # use the "p" GET or POST param req = Rack::Request.new(env) req.params['p'].to_i if req.params.has_key?('p') else # use the "p=â?¦" command line argument p_param = nil p_param.to_i if $*.detect {|a| p_param = a[/^p=(\S+)$/, 1] } end || page_range.first # make sure the page is within the range page_number = page_range.first unless page_range.member?(page_number) # create an input hash searching for "The King" and paginating the results pagination_input_hash = { 'keywords' => 'The King', 'paginationInput' => { 'entriesPerPage' => 30, 'pageNumber' => page_number } } # convert it to JSON pagination_input_json = pagination_input_hash.to_json # open a connection to Bonanza's API and send the request pagination_response = Net::HTTP.new("api.bonanza.com").post( '/api_requests/standard_request', "findItemsByKeywords=#{pagination_input_json}", {'X-BONANZLE-API-DEV-NAME' => 'elvis_collector_dev'} ) # get the response data back as JSON pagination_response_json = pagination_response.body # convert the response data back to a hash pagination_response_hash = JSON.parse(pagination_response_json) # check if we got a response back if pagination_response_hash['ack'] == 'Success' && pagination_response_hash.has_key?('findItemsByKeywordsResponse') # output links to each page puts %[<div style="margin-bottom: 1em;">] page_range.to_a.each do |p_i| if p_i == page_number puts %[<span>#{p_i}</span>] else puts %[<a href="?p=#{p_i}">#{p_i}</a>] end end puts %[</div>] # output pictures of each item pagination_response_hash['findItemsByKeywordsResponse']['item'].each do |item| item_url = item['viewItemURL'] item_img = item['galleryURL'] puts %[<a href="#{item_url}" style="float: left;">] puts %[ <img src="#{item_img}"/>] puts %[</a>] end else # helpful error message in the case of a bad response from Bonapitit puts %[The request to Bonapitit failed.<br/>] puts %[Did you forget to fill in the 'X-BONANZLE-API-DEV-NAME'?<br/>] puts %[#{CGI.escapeHTML(pagination_response_hash.to_yaml)}] end
Data
pagination_input_json's value (JSON):
{"paginationInput":{"pageNumber":1,"entriesPerPage":30},"keywords":"The King"}
<div style="margin-bottom: 1em;"> <a href="?p=1">1</a> <span>2</span> <a href="?p=3">3</a> <a href="?p=4">4</a> â?¦ <a href="?p=49">49</a> <a href="?p=50">50</a> </div> <a href="https://www.bonanza.com/booths/tshirt_seller_dev/items/CHESS__THE_KING__LOGO_Royal_Blue_T_SHIRT" style="float: left;"> <img src="http://s3.amazonaws.com/bonanzaimages/afu/images/2889/3800/shirt-chess-king_thumb155_crop.jpg"/> </a> <a href="https://www.bonanza.com/booths/dvd_fan_jan/items/King_of_Comedy_DVD_Robert_De_Niro_Jerry_Lewis" style="float: left;"> <img src="http://s3.amazonaws.com/bonanzaimages/afu/images/3403/7889/p1160985_thumb155_crop.jpg"/> </a> â?¦ <a href="https://www.bonanza.com/booths/where_the_wild_books_are/items/The_King_is_Naked_" style="float: left;"> <img src="http://s3.amazonaws.com/bonanzaimages/afu/images/2261/5446/DSCF4234_3321_thumb155_crop.JPG"/> </a>
Sample: Proximity Search
Retrieves items based on keywords provided and sorted by distance from the buyer.
Task
You want to search Bonanza for items matching the keywords "The King" near Memphis, TN and show thumbnails of each item, linked to the item pages. Additionally, the further the item is from the Memphis, the more it's opacity should be faded out. Items beyond 100 miles away are filtered out completely.
Code
Basic Ruby keyword search script from the previous example, with pagination added:
require 'rubygems' require 'json' # Hash#to_json(), JSON.parse() require 'net/http' # Net::HTTP#post() require 'cgi' # CGI.escapeHTML() # set up our max distance max_distance = 100 # create an input hash searching for "The King" near zip code "37501" proximity_input_hash = { 'keywords' => 'The King', 'buyerPostalCode' => '37501', 'sortOrder' => 'Distance', 'itemFilter' => { 'name' => 'maxDistance', 'value' => max_distance }, 'paginationInput' => { 'entriesPerPage' => 100 } } # convert it to JSON proximity_input_json = proximity_input_hash.to_json # open a connection to Bonanza's API and send the request proximity_response = Net::HTTP.new("api.bonanza.com").post( '/api_requests/standard_request', "findItemsByKeywords=#{proximity_input_json}", {'X-BONANZLE-API-DEV-NAME' => 'elvis_collector_dev'} ) # get the response data back as JSON proximity_response_json = proximity_response.body # convert the response data back to a hash proximity_response_hash = JSON.parse(proximity_response_json) # check if we got a response back if proximity_response_hash['ack'] == 'Success' && proximity_response_hash.has_key?('findItemsByKeywordsResponse') # output pictures of each item proximity_response_hash['findItemsByKeywordsResponse']['item'].each do |item| item_url = item['viewItemURL'] item_img = item['galleryURL'] item_opacity = 1.0 - item['distance'].to_f / max_distance.to_f puts %[<a href="#{item_url}" style="opacity: #{item_opacity};">] puts %[ <img src="#{item_img}" style="width: 32px; height: 32px;"/>] puts %[</a>] end else # helpful error message in the case of a bad response from Bonapitit puts %[The request to Bonapitit failed.<br/>] puts %[Did you forget to fill in the 'X-BONANZLE-API-DEV-NAME'?<br/>] puts %[#{CGI.escapeHTML(proximity_response_hash.to_yaml)}] end
Data
proximity_input_json's value (JSON):
{"itemFilter":{"name":"maxDistance","value":100},"buyerPostalCode":"37501","paginationInput":{"entriesPerPage":100},"sortOrder":"Distance","keywords":"The King"}
<a href="https://www.bonanza.com/booths/davidhp/items/Bernard_King_Autographed_With_Crown" style="opacity: 0.98;"> <img src="http://s3.amazonaws.com/bonanzaimages/afu/images/0428/4761/1856800_thumb155_crop.jpg" style="width: 32px; height: 32px;"/> </a> <a href="https://www.bonanza.com/booths/katrina9799/items/The_Lion_King_Plastic_Toy_bank" style="opacity: 0.97;"> <img src="http://s3.amazonaws.com/bonanzaimages/afu/images/2669/5371/9890_35_thumb155_crop.jpg" style="width: 32px; height: 32px;"/> </a> â?¦ <a href="https://www.bonanza.com/booths/AchetezCeci/items/DC_Adventure_Comic_375_King_of_the_Legion" style="opacity: 0.08;"> <img src="http://s3.amazonaws.com/bonanzaimages/afu/images/2178/5264/Adventure_375_thumb155_crop.jpg" style="width: 32px; height: 32px;"/> </a> <a href="https://www.bonanza.com/booths/happyhourcomics/items/King_Kong_Animated_Series_Vol_1_DVD" style="opacity: 0.03;"> <img src="http://s3.amazonaws.com/bonanzaimages/afu/images/2617/3216/image-1_thumb155_crop.jpg" style="width: 32px; height: 32px;"/> </a>
Ruby Example for getCategories
Sample: Getting Categories
Code
Ruby script to get information of all children categories of the provided categoryID:
require 'rubygems' require 'json' # Hash.to_json(), JSON.parse() require 'net/http' # Net::HTTP#post() require 'cgi' # CGI.escapeHTML() header = {'X-BONANZLE-API-DEV-NAME' => 'my_dev_name'} request_name = 'getCategoriesRequest' # create an input hash searching for 'Baby' category (2984) input_hash = { 'categoryParent' => 2984 } # convert the hash to JSON input_json = input_hash.to_json # open a connection to Bonanza's API and send the request response = Net::HTTP.new('api.bonanza.com').post( '/api_requests/standard_request', "#{request_name}=#{input_json}", header ) # get response data back as JSON response_json = response.body # convert response data back to a hash response_hash = JSON.parse(response_json) # check if we got a response back if response_hash['ack'] == 'Success' && response_hash.has_key?('getCategoriesResponse') response = response_hash['getCategoriesResponse'] response['categoryArray'].each do |category| puts "Category ID: #{category['categoryId']}" puts "Category Name: #{category['categoryName']}" end else # helpful error message in case of bad response from Bonapitit puts "The request to Bonapitit failed.<br/>" puts "Did you forget to send a categoryParent?<br/>" puts CGI.escapeHTML(response_hash.to_yaml) end
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 } ] } }
Ruby Example for getOrders
Sample: Getting Orders
Code
Ruby script to get order information for a seller in a specific time period
require 'rubygems' require 'json' # Hash.to_json(), JSON.parse() require 'net/http' # Net::HTTP#post() require 'cgi' # CGI.escapeHTML() 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_hash = { requesterCredentials: { bonanzleAuthToken: "my_auth_token" }, orderRole: 'seller', soldTimeFrom: '2013-01-13', soldTimeTo: '2016-01-13' } # convert the hash to JSON input_json = input_hash.to_json # open a connection to Bonanza's API and send the request response = Net::HTTP.new('api.bonanza.com').post( '/api_requests/secure_request', "#{request_name}=#{input_json}", header ) # get response data back as JSON response_json = response.body # convert response data back to a hash response_hash = JSON.parse(response_json) # check if we got a response back if response_hash['ack'] == 'Success' && response_hash.has_key?('getOrdersResponse') response = response_hash['getOrdersResponse'] # print results response['orderArray'].each do |order_hash| order = order_hash['order'] puts "Order #{order['orderID']}------------------" puts "Buyer Username: #{order['buyerUserName']}" puts "Amount Paid: #{order['amountPaid']}" puts "Checkout Status: #{order['checkoutStatus']['status']}" puts "Created Time: #{order['createdTime']}" puts end else # helpful error message in case of bad response from Bonapitit puts "The request to Bonapitit failed.<br/>" puts CGI.escapeHTML(response_hash.to_yaml) end
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 } }
Ruby Example for setNotificationPreferences
Sample: Setting notification preferences
Code
Ruby code to register a URL to listen for seller question/feedback notifications
require "json" # Hash.to_json(), JSON.parse() require "net/http" # Net::HTTP#post() headers = { "X-BONANZLE-API-DEV-NAME" => "your_dev_id", "X-BONANZLE-API-CERT-NAME" => "your_cert_id", "Content-Type" => "application/json" } request_name = "setNotificationPreferencesRequest" input_hash = { "requesterCredentials" => { "bonanzleAuthToken" => "your_token" }, "applicationDeliveryPreferences" => { "applicationEnable" => "Enable", "deliveryURLDetails" => { "deliveryURL" => "http://foo.com/notifications", "status" => "Enable" } }, "userDeliveryPreferenceArray" => { "notificationEnable" => [ { "eventEnable" => "Enable", "eventType" => "askSellerQuestion" }, { "eventEnable" => "Enable", "eventType" => "feedback" } ] } } # convert the hash to JSON input_json = input_hash.to_json payload = { request_name => input_hash }.to_json # open a connection to Bonanza's API http = Net::HTTP.new("api.bonanza.com", 443) http.use_ssl = true # Make POST request response = http.post("/api_requests/secure_request", payload, headers) # get response data back as JSON response_json = response.body # convert response data back to a hash response_hash = JSON.parse(response_json) # check if we got a response back if response_hash["ack"] == "Success" && response_hash["setNotificationPreferencesResponse"] response = response_hash["setNotificationPreferencesResponse"] puts response else puts "The request to Bonapitit failed." puts response_hash["errorMessage"]["message"] end
Data
response_json's value (JSON [formatted for legibility]):
{ "ack":"Success", "version":"1.0", "timestamp":"2018-02-19T07:26:57.000Z", "setNotificationPreferencesResponse": { "notificationId":69438, "deliveryURLsProcessed":1, "eventsProcessed":2 } }