Create Your Own Client Library
You can create your own client library to use with the Newegg Marketplace API. Your code should construct and sign a request in the format expected by the Newegg Marketplace API, and then you can parse the XML response. You can access the Newegg Marketplace API by following steps:
Step 1- Determine the correct Newegg Marketplace API URL to use.
Step 2- Specify the parameter value in the request URL.
Step 3- Specify the correct HTTP request method and the xml/Json content types that are accepted.
Step 4- Attach your API Key and the Secret Key in requests (refer to authentication examples above).
Step 5- Construct the request body as required. Submit the HTTP request.
Step 6- Parse the response.
Request Format
Newegg Marketplace API supports query/update requests for calling Restful service actions. Query requests are simple HTTP requests, using the GET or POST method with query parameters in the URL or HTTP body respectively. Update requests using the PUT or DELETE method with updated parameters in the URL or HTTP body respectively.
Newegg Marketplace API requires the use of HTTPS in order to prevent third-party eavesdropping on your communication with Newegg.
Create a HTTP Request
To create a Newegg Marketplace API query/update request, you need to first construct a correctly formatted request URL. You can refer to the URL template of the API services you want to use (please refer to the API reference section).
Below are the possible value lists in your HTTP request
Name |
Required? | Description |
Request URL | Yes | The Newegg Marketplace API service endpoint you are using |
Request Method | Yes | The GET/POST or PUT/DELETE method of the API service required |
Body Content-type | No | The XML/Json format of the content in the request body. The default is XML. |
Response Content-type | No | The XML/Json format of the content in the response. The default is XML. |
Authentication header | Yes | Format: Authorization:{api-key}
The API key of the authorized API developer |
SecretKey header | Yes | Format: Secretkey:{secretkey}
The secret key of an authorized API developer |
RAW body | No
|
Pass parameters by the request body. The format of the content should conform to the specification of the API service. |
Note: The API reference section includes the important information for each API function for your reference.
Example:
GET Https://api.newegg.com/marketplace/ordermgmt/orderstatus/orders/{ordernumber}?sellerid={sellerid} Authorization: 720ddc067f4d115bd544aff46bc75634 SecretKey: 21EC2020-3AEA-1069-A2DD-08002B30309D Content-Type: application/xml Accept: application/xml
HTTP method – specifies which request method.
Authentication — indicates this service needs an authentication to use.
Request Formats – the request parameters format in the request body.
Response Formats – the supported format of the response content.
Rate Limited – API Request Limit
Request Parameters:
URL Parameters – the required parameters in the request URL.
Request Parameters – some specific parameters in the request body. The format shall be XML or Json; you can get the supported type from the “request format” in the URL Resource Information section above.
Note: Please make sure your request URL is all in lower case (except for Seller ID) and cannot contain any blank spaces or line breaks.
Bad Request
Newegg Marketplace API will return a bad request (HTTP status code = 400) if you submitted an inappropriate request in the following types:
- Illegal request body. Such as not well-formatted XML or incorrect tag or data type.
Example: XML, Response
<?xml version="1.0" encoding="utf-8"?> <Errors> <Error> <Code>CE003</Code> <Message>XML parsing error. The 'NeweggAPIRequest1' start tag on line 1 position 2 does not match the end tag of 'NeweggAPIRequest'. Line 1, position 451.</Message> </Error> </Errors>
Example: Json, Response
[ { "Code": "CE003", "Message": "XML parsing error. The 'NeweggAPIRequest1' start tag on line 1 position 2 does not match the end tag of 'NeweggAPIRequest'. Line 1, position 451." } ]
- Business validation failure. Invalid data request or fail to match business requirement. For the detail error code and message please refer to the “Request Failure Errors” part at the end of every service definition.
Example: XML, Response
<?xml version="1.0" encoding="utf-8" ?> <Errors> <Error> <Code>SO011</Code> <Message>Only unshipped orders can be shipped. The order status is currently Closed</Message> </Error> </Errors>
Example: Json, Response
[ { "Code": "SO011", "Message": "Only unshipped orders can be shipped. The order status is currently Closed" } ]
In order to parse error messages in your own programs correctly, please refer to “Exception Handling for Bad Request” in the Code Examples section.
Code Examples
Please note that these examples are provided to you with the simple purpose of demonstrating how you can use Newegg Marketplace API functions and resources. The examples do not take in consideration of extra requirements such as authentication/security required by each programming language.
C# Example
The code example below demonstrates how to query the inventory quantity of the specified Newegg Item “9SIA00600000023” for the seller “A006” in .NET C#
- Create a new class to de-serialize the response
Example: C#, Inventory response entity
public class InventoryResult { public string SellerID { get; set; } public string ItemNumber { get; set; } public int AvailableQuantity { get; set; } public string Active { get; set; } public string SellerPartNumber { get; set; } public string ShipByNewegg { get; set; } }
2. Get the inventory available quantity
Example: C#, Get Item Inventory
Console.WriteLine(string.Format("Newegg Marketplace API - Get Inventory request at:{0}", DateTime.Now.ToString())); Console.WriteLine(""); Console.WriteLine("*********************************************************************"); Console.WriteLine(""); try { InventoryResult inventoryResult = null; //Determine the correct Newegg Marketplace API endpoint to use. // Please make sure your request URL is all in lower case string endpoint = @"https://api.newegg.com/marketplace/contentmgmt/item/inventory?sellerid={0}"; endpoint = String.Format(endpoint, "A006"); //Create an HttpWebRequest System.Net.HttpWebRequest request = System.Net.WebRequest.Create(endpoint) as HttpWebRequest; //Remove proxy request.Proxy = null; //Specify the request method request.Method = "POST"; //Specify the xml/Json request and response content types. request.ContentType = "application/xml"; request.Accept = "application/xml"; //Attach authorization information request.Headers.Add("Authorization", "your API-key here"); request.Headers.Add("Secretkey", "your secretkey here"); //Construct the query criteria in the request body string requestBody = @" <ContentQueryCriteria> <Type>1</Type> <Value>A006ZX-35833</Value> </ContentQueryCriteria>"; byte[] byteStr = Encoding.UTF8.GetBytes(requestBody); request.ContentLength = byteStr.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(byteStr, 0, byteStr.Length); } //Parse the response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { Console.WriteLine(String.Format("Code:{0}.Error:{1}", response.StatusCode.ToString(), response.StatusDescription)); return; } using (Stream responseStream = response.GetResponseStream()) { XmlSerializer serializer = new XmlSerializer(typeof(InventoryResult)); inventoryResult = serializer.Deserialize(responseStream) as InventoryResult; } } string sellerID = inventoryResult.SellerID; string itemNumber = inventoryResult.ItemNumber; int availableQuantity = inventoryResult.AvailableQuantity; string message = String.Format("SellerID:{0} ItemNumber:{1} Availble Quantity:{2} \r\n Active:{3} SellerPartNumber:{4} ShipByNewegg:{5}", inventoryResult.SellerID, inventoryResult.ItemNumber, inventoryResult.AvailableQuantity, inventoryResult.Active, inventoryResult.SellerPartNumber, inventoryResult.ShipByNewegg); Console.WriteLine(message); } catch (WebException we)//Error Handling for Bad Request { if (((WebException)we).Status == WebExceptionStatus.ProtocolError) { WebResponse errResp = ((WebException)we).Response; using (Stream respStream = errResp.GetResponseStream()) { StreamReader reader = new StreamReader(respStream); Console.WriteLine(String.Format("{0}", reader.ReadToEnd())); } } } catch (Exception ex)//unhandle error { Console.WriteLine(string.Format("exception: at time:{0}", DateTime.Now.ToString())); Console.WriteLine(ex.Message + "---->"); Console.WriteLine(ex.StackTrace.ToString()); } Console.WriteLine(""); Console.WriteLine("*********************************************************************"); Console.WriteLine(""); Console.WriteLine("Please input any key to exit……"); Console.ReadLine();
Error Handling for Bad Request (Status Code = 400)
try { //Your code here } catch (WebException we)//Error Handling for Bad Request { if (((WebException)we).Status == WebExceptionStatus.ProtocolError) { WebResponse errResp = ((WebException)we).Response; using (Stream respStream = errResp.GetResponseStream()) { StreamReader reader = new StreamReader(respStream); Console.WriteLine(String.Format("{0}", reader.ReadToEnd())); } } }
Java Example
The following example demonstrates how to retrieve order information through Newegg Marketplace API in Java.
/* * To change this template, choose Tools | Templates * And open the template in the editor. */ package marketplaceapi_java_demo; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.security.cert.X509Certificate; import java.util.Calendar; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class MarketplaceAPI_Java_Demo { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception{ GetOrderInfo(); } private static void GetOrderInfo() throws Exception{ System.out.println("[" + Calendar.getInstance().getTime() + "]Newegg Marketplace API - GetOrderInfo:"); System.out.println("-----------------------------------"); String requestUrl = "https://api.newegg.com/marketplace/ordermgmt/order/orderinfo?sellerid=A006"; try { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); URL url = new URL(requestUrl); HttpsURLConnection httpsConnection = (HttpsURLConnection)url.openConnection(); //javax.net.ssl. = false; //Set accepted format in response message:application/xml|application/json httpsConnection.setRequestProperty("Accept", "application/xml"); //Set the accepted format in request body:application/xml|application/json httpsConnection.setRequestProperty("content-type", "application/xml"); //Set the request method:GET|PUT|POST httpsConnection.setRequestMethod("PUT"); //Set authorization key httpsConnection.setRequestProperty("Authorization", "720ddc067f4d115bd544aff46bc75634"); //Set secret-key httpsConnection.setRequestProperty("SecretKey", "21EC2020-3AEA-1069-A2DD-08002B30309D"); httpsConnection.setDoInput(true); httpsConnection.setDoOutput(true); String requestStr = "<NeweggAPIRequest>" + "<OperationType>GetOrderInfoRequest</OperationType>" + "<RequestBody>" + "<PageIndex>1</PageIndex>" + "<PageSize>10</PageSize>" + "<RequestCriteria>" + "<OrderNumberList>" + "<OrderNumber>159243598</OrderNumber>" + "<OrderNumber>41473642</OrderNumber>" + "</OrderNumberList>" + "<Status>1</Status>" + "<Type>1</Type>" + "<OrderDateFrom>2011-01-01 09:30:47</OrderDateFrom>" + "<OrderDateTo>2011-12-17 09:30:47</OrderDateTo>" + "<OrderDownloaded>0</OrderDownloaded>" + "</RequestCriteria>" + "</RequestBody>" + "</NeweggAPIRequest>"; byte[] requestBody = requestStr.getBytes(); //Set content-length httpsConnection.setRequestProperty("Content-Length", String.valueOf(requestBody.length)); OutputStream outStream = httpsConnection.getOutputStream(); outStream.write(requestBody); outStream.close(); InputStreamReader inputReader = new InputStreamReader(httpsConnection.getInputStream()); BufferedReader reader = new BufferedReader(inputReader); String responseBody = ""; while(reader.ready()){ responseBody += reader.readLine(); } reader.close(); inputReader.close(); System.out.println("[" + Calendar.getInstance().getTime() + "]Response Message:"); System.out.println("-----------------------------------"); System.out.println(responseBody); } catch (MalformedURLException ex) { System.out.println("Illegal request URI:" + ex.getMessage()); } catch(Exception e){ System.out.println("Exception:" + e.getMessage()); //Error Handling for Bad Request InputStreamReader errorReader = new InputStreamReader(httpsConnection.getErrorStream()); BufferedReader bufferReader = new BufferedReader(errorReader); String errorMsg = ""; while(bufferReader.ready()){ errorMsg += bufferReader.readLine(); } bufferReader.close(); errorReader.close(); System.out.println(errorMsg); } } }
Error Handling for Bad Request (Status Code = 400)
try { //Your code here } catch(Exception e){ System.out.println("Exception:" + e.getMessage()); //Error Handling for Bad Request InputStreamReader errorReader = new InputStreamReader(httpsConnection.getErrorStream()); BufferedReader bufferReader = new BufferedReader(errorReader); String errorMsg = ""; while(bufferReader.ready()){ errorMsg += bufferReader.readLine(); } bufferReader.close(); errorReader.close(); System.out.println(errorMsg); }
PHP Example
The code example below demonstrates how to access Newegg API with PHP curl extension under windows operation system.
Step 1- Download php_curl.dll
Step 2- Edit php.ini and apply the extension:
Extension=php_curl.dll
Step 3- Restart the Apache server
Example: PHP, Get order status
GET: <?php // Request Newegg API! REST Web Service using // HTTP POST with curl. PHP4/PHP5 // Allows retrieval of HTTP status code for error reporting error_reporting(E_ALL); $SellerID = 'A006'; // The POST URL and parameters // Please make sure your request URL is all in lower case $request = 'https://api.newegg.com/marketplace/ordermgmt/orderstatus/orders/12345678?sellerid='.$SellerID; $header_array =array('Content-Type:application/xml', 'Accept:application/xml', 'Authorization: your API-key here', 'SecretKey: your secretkey here'); try { // Get the curl session object $session = curl_init($request); // Set the POST options. curl_setopt($session, CURLOPT_HEADER, 1); curl_setopt($session,CURLOPT_HTTPHEADER,$header_array); curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); curl_setopt($session, CURLOPT_SSL_VERIFYPEER, 0); // Do the POST and then close the session $response = curl_exec($session); curl_close($session); print $response; } catch (InvalidArgumentException $e) { curl_close($session); throw $e; } catch (Exception $e) { curl_close($session); throw $e; } ?>
Example: PHP, Get item inventory
POST: <?php // Request Newegg API! REST Web Service using // HTTP POST with curl. PHP4/PHP5 // Allows retrieval of HTTP status code for error reporting error_reporting(E_ALL); $SellerID = 'A006'; // The POST URL and parameters // Please make sure your request URL is all in lower case $request = 'https://api.newegg.com/marketplace/contentmgmt/item/inventory?sellerid='.$SellerID; $body = '<ContentQueryCriteria> <Type>0</Type> <Value>9SIA08I0492622</Value> </ContentQueryCriteria>'; $header_array =array('Content-Type:application/xml', 'Accept:application/xml', 'Authorization: your API-key here', 'SecretKey: your secretkey here'); try { // Get the curl session object $session = curl_init($request); $putString = stripslashes($body); $putData = tmpfile(); fwrite($putData, $putString); fseek($putData, 0); // Set the POST options. curl_setopt($session, CURLOPT_HEADER, 1); curl_setopt($session,CURLOPT_HTTPHEADER,$header_array); curl_setopt($session, CURLOPT_POST, true); curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); curl_setopt($session, CURLOPT_POSTFIELDS, $body); curl_setopt($session, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($session, CURLOPT_INFILE, $putData); curl_setopt($session, CURLOPT_INFILESIZE, strlen($putString)); // Do the POST and then close the session $response = curl_exec($session); curl_close($session); print $response; } catch (InvalidArgumentException $e) { curl_close($session); throw $e; } catch (Exception $e) { curl_close($session); throw $e; } ?>
Example: PHP, Update inventory and price
PUT: <?php // Request Newegg API! REST Web Service using // HTTP POST with curl. PHP4/PHP5 // Allows retrieval of HTTP status code for error reporting error_reporting(E_ALL); $SellerID = 'A006'; // The POST URL and parameters // Please make sure your request URL is all in lower case $request = 'https://api.newegg.com/marketplace/contentmgmt/item/inventoryandprice?sellerid='.$SellerID; $body = '<ItemInventoryAndPriceInfo> <Type>1</Type> <Value>A006testitem201201021459</Value> <Condition>1</Condition> <Inventory>200</Inventory> <MSRP>34.98</MSRP> <SellingPrice>29.92</SellingPrice> <EnableFreeShipping>1</EnableFreeShipping> <Active>0</Active> </ItemInventoryAndPriceInfo>'; $header_array =array('Content-Type:application/xml', 'Accept:application/xml', 'Authorization: your API-key here', 'SecretKey: your secretkey here'); try { // Get the curl session object $session = curl_init($request); $putString = stripslashes($body); $putData = tmpfile(); fwrite($putData, $putString); fseek($putData, 0); // Set the POST options. curl_setopt($session, CURLOPT_HEADER, 1); curl_setopt($session,CURLOPT_HTTPHEADER,$header_array); curl_setopt($session, CURLOPT_PUT, true); curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); curl_setopt($session, CURLOPT_POSTFIELDS, $body); curl_setopt($session, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($session, CURLOPT_INFILE, $putData); curl_setopt($session, CURLOPT_INFILESIZE, strlen($putString)); // Do the POST and then close the session $response = curl_exec($session); curl_close($session); print $response; } catch (InvalidArgumentException $e) { curl_close($session); throw $e; } catch (Exception $e) { curl_close($session); throw $e; } ?>
The code example below demonstrates how to access Newegg API with pecl http request extension under LINUX system.
- Download pecl_http extension from http://pecl.php.net/package/pecl_http, get the latest stable version.
- Install the extension( refer to : http://www.zipservers.com/community/showthread.php?59-How-to-install-PECL-Modules-on-Linux )
[root@server ]# cd /root/ ; wget http://pecl.php.net/get/pecl_http-1.6.5.tgz [root@server ]# tar -zxvf pecl_http-1.6.5.tgz [root@server ]# cd pecl_http-1.6.5 [root@server ]# phpize [root@server ]# ./configure [root@server ]# make [root@server ]# make test [root@server ]# make install [root@server ]# php -i | grep “Configuration File” Configuration File (php.ini) Path => /usr/local/lib Loaded Configuration File => /usr/local/lib/php.ini
3. Switch on the extension in the php.ini
[root@server ]# vi /usr/local/lib/php.ini And add extension=http.so
4. Restart the Apache server
Example: PHP, Get Item Inventory
<?php //request url // Please make sure your request URL is all in lower case $url = " https://api.newegg.com/marketplace/contentmgmt/item/inventory?sellerid=A006"; //set the api-key & secret-key $header_array = array('Authorization' => '{your API-key here}', 'Secretkey' => '{your secret-key here}'); //set the body if necessary $body = "<ContentQueryCriteria> <Condition>1</Condition> <Type>0</Type> <Value>9SIA0B992342342</Value> </ContentQueryCriteria>"; $options = array(headers => $header_array); //create the httprequest object //specfiy the request method:HTTP_METH_GET|HTTP_METH_POST|HTTP_METH_PUT $httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options); //add the content type $httpRequest_OBJ->setContentType = 'Content-Type: text/xml'; //add the raw post data //$httpRequest_OBJ->setRawPostData ($body); $httpRequest_OBJ->setBody ($body); try { //send the http request $result = $httpRequest_OBJ->send(); }catch(HttpException $ex) { if (isset($ex->innerException)){ echo $ex->innerException->getMessage(); exit; } else { echo $ex; exit; } } $response_code = $httpRequest_OBJ->getResponseCode(); if($response_code == "200") { //reqeust success echo $response_code; echo $httpRequest_OBJ->getResponseBody(); } else { //failure echo $response_code; echo $httpRequest_OBJ->getResponseBody(); } ?>
Error Handling for Bad Request (Status Code = 400)
// Do the POST and then close the session $response = curl_exec($session); curl_close($session); //The error message will be stored in this variable if it’s a bad request print $response;
Python Example
The code example below demonstrates how to access Newegg API in Python.
Example: Python, Get Item Price
import httplib2 #import pyodbc import string all_items_location_id=521799450 # whether to print item data retrieved from database print_item_data=True # items data retrieved from database items=[] def _put_call(url, xmlfeed): h = httplib2.Http(".cache",disable_ssl_certificate_validation=True) resp, content = h.request(url, "POST", body=xmlfeed, headers={'content-type':'application/xml','Authorization': 'your API-key here', 'Secretkey':'your secretkey here' } ) print "response header from Newegg:", resp print "response body from Newegg:", content def get_price(): header = '<?xml version="1.0" encoding="UTF-8"?>' xmlfeed=[] xmlfeed.append(header) xmlfeed.append('<ContentQueryCriteria>') xmlfeed.append('<Type>1</Type>') xmlfeed.append('<Value>TCR8996</Value>') xmlfeed.append('</ContentQueryCriteria>') xmlfeed=string.join(xmlfeed,'') print "Get item price:" put_call_url = 'https://api.newegg.com/marketplace/contentmgmt/item/price?sellerid=A006' _put_call(put_call_url,xmlfeed) get_price()
Error Handling for Bad Request (Status Code = 400)
def _put_call(url, xmlfeed): h = httplib2.Http(".cache",disable_ssl_certificate_validation=True) resp, content = h.request(url, "POST", body=xmlfeed, headers={'content-type':'application/xml','Authorization': 'your API-key here', 'Secretkey':'your secretkey here' } ) print "response header from Newegg:", resp #The error message will be stored in this variable if it’s a bad request print "response body from Newegg:", content
Last updated: October 15, 2018