Code Examples (calling the Quote Service)

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
    public static void main(String[] args) {
        Parcel request = new Parcel(1000);
        request.Quote();
    }
}
public class Parcel {
    
    protected String _key;
    protected String _webservice;
    protected int _parcel;
    
    public Parcel(int parcel){
        this._key = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
        this._webservice = "http://webservices.i-parcel.com/api/";
        this._parcel = parcel;
    }
    public void Quote() {
          try {
                URL url = new URL(this._webservice+"Quote");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                
                StringBuilder input = new StringBuilder("{");
                input.append("\"SessionID\": \"\", ");
                input.append("\"key\": \""+this._key+"\", ");
                input.append("\"ParcelID\":"+this._parcel);
                input.append("}");
                
                System.out.println("Request content:");
                System.out.println(input.toString()+"\n");
                //{"SessionID": "", "key": "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE", "ParcelID":1000}
                 
                OutputStream os = conn.getOutputStream();
                os.write(input.toString().getBytes());
                os.flush();
                
                if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                }
                
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         
                String output;
                System.out.println("Response:");
                while ((output = br.readLine()) != null) {
                    System.out.println(output);
                }
         
                conn.disconnect();
         
              } catch (MalformedURLException e) {
         
                e.printStackTrace();
         
              } catch (IOException e) {
         
                e.printStackTrace();
         
             }
    }
}

JavaScript (JQuery AJAX)

var webServiceAddress = window.location.protocol + //webservices.i-parcel.com/api/;
var request =
    {
        key: '"AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"',
        SessionID: '',
        ParcelID: 1000
    }
/*IE8*/
if ('XDomainRequest' in window && window.XDomainRequest !== null || typeof $ != "function") {
    var xdr = new window.XDomainRequest();
    xdr.open('POST', window.location.protocol + webServiceAddress + "Quote");
    xdr.onload = function () {
        console.log(JSON.parse(xdr.responseText));
    };
    xdr.onerror = function () {
        window.console.warn(xdr);
    }
    xdr.send(json);
} else {
/*JQuery*/
    $.ajax({
        type: 'POST',
        url: window.location.protocol + webServiceAddress + "Quote",
        dataType: "json",
        data: json,
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            console.log(response);
        },
        error: function (response) {
            console.warn(response);
        }
    });
}

Labels, working example

C♯

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace GetLabel
{
    /// <summary>Puts a label in the Documents folder</summary>
    class Program
    {
        static void Main()
        {
            const string trackingNumber = "0362951060760US";
            const string apiKey = "2abb41e7-25e6-4f3d-b341-d9dacaab6a77"; 
            const string fileType = "image/png"; //can also be image/jpeg, image/bmp, image/gif, application/pdf
            var outputDirectory = Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents");
            var request = new
            {
                Key = apiKey,
                TrackingNumber = trackingNumber
            };
            var requestAsJson = JsonConvert.SerializeObject(request);
            var requestAsBytes = Encoding.GetEncoding("utf-8").GetBytes(requestAsJson);
            var apiRequest = (HttpWebRequest) WebRequest.Create("https://webservices.i-parcel.com/api/GetLabel/");
            apiRequest.Method = "POST";
            apiRequest.ContentLength = requestAsJson.Length;
            apiRequest.ContentType = "application/json";
            apiRequest.Accept = fileType;
            using (var stream = apiRequest.GetRequestStream())
            {
                stream.Write(requestAsBytes, 0, requestAsJson.Length);
            }
            using (var webresponse = apiRequest.GetResponse())
            {
                var responseStream = webresponse.GetResponseStream();
                if (responseStream == null) return;
                using(var file = File.Create(string.Format(@"{0}\{1}.{2}", outputDirectory, request.TrackingNumber, GetExtension(fileType))))
                {
                    CopyStream(responseStream, file);
                }
            }
        }
        private static string GetExtension(string input)
        {
            var match = new Regex(@"\w\w\w\w?$").Match(input).Value;
            return match == "jpeg" ? "jpg" : match;
        }
        private static void CopyStream(Stream input, Stream output)
        {
            var buffer = new byte[8 * 1024];
            int len;
            while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, len);
            }    
        }
    }
}

Bulk cancellation

JavaScript

//config
var apiKey = "7301b908-bde1-4adb-9e27-57607756ec6a";
var reason = "cancelled by Todd Ester (tester@iparcel.com), see ticket #123456";
var trackings = [
  "0360593696254US", "0360593694234US"
];
//end config

for (var i = 0; i < trackings.length; i++) {
    fetch("https://webservices.i-parcel.com/api/Cancel",
        {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(
                {
                    Key: apiKey,
                    TrackingNumber: trackings[i],
                    UserNotes: reason
                }
            )
        }
    ).then(function (r) {
        console.log(r.statusText);
    });
}

Quote

C♯

using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
namespace i_parcelAPIConsumer
{
    class Program
    {
        static void Main(string[] args)
        {
            QuoteRequest quoteRequest = new QuoteRequest();
            quoteRequest.key = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";
            quoteRequest.ItemDetailsList = new List<ItemDetails>();
            quoteRequest.ItemDetailsList.Add(new ItemDetails()
            {
                SKU = "SKUCODE",
                Quantity = 10,
            });
            quoteRequest.AddressInfo = new AddressInfo();
            quoteRequest.AddressInfo.Shipping = new Address()
            {
                FirstName = "TEST",
                LastName = "TEST",
                Street1 = "Test Road 1",
                Street2 = "Test Road 2",
                City = "Prospect",
                PostCode = "11111",
                Region = "NW",
                CountryCode = "AU",
                Email = "test@test.com",
                Phone = "111-111-1111"
            };
            quoteRequest.AddressInfo.Billing = new Address()
            {
                FirstName = "TEST",
                LastName = "TEST",
                Street1 = "Test Road 1",
                Street2 = "Test Road 2",
                City = "Prospect",
                PostCode = "11111",
                Region = "NW",
                CountryCode = "AU",
                Email = "test@test.com",
                Phone = "111-111-1111"
            };
            quoteRequest.DDP = true;
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Encoding = Encoding.UTF8;
                client.BaseAddress = "https://webservices.i-parcel.com/";
                var request = new JavaScriptSerializer().Serialize(quoteRequest);
                var response = "";
                try
                {
                    response = client.UploadString(client.BaseAddress + "api/Quote", "POST", request);
                    var quoteResponse = new JavaScriptSerializer().Deserialize<QuoteResponse>(response);
                    //Process response
                }
                catch (Exception ex)
                {
                    //Handle Exception
                }
            }
        }
        #region Request Classes
        public class QuoteRequest
        {
            public string key { get; set; }
            public List<ItemDetails> ItemDetailsList { get; set; }
            public AddressInfo AddressInfo { get; set; }
            public bool DDP { get; set; }
            public decimal OtherDiscount { get; set; }
            public string OtherDiscountCurrency { get; set; }
            public string PromoCode { get; set; }
        }
        public class ItemDetails
        {
            public string SKU { get; set; }
            public int Quantity { get; set; }
        }
        public class AddressInfo
        {
            public Address Shipping { get; set; }
            public Address Billing { get; set; }
        }
        public class Address
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Street1 { get; set; }
            public string Street2 { get; set; }
            public string PostCode { get; set; }
            public string City { get; set; }
            public string Region { get; set; }
            public string CountryCode { get; set; }
            public string Email { get; set; }
            public string Phone { get; set; }
        }
        #endregion
        #region Response Classes
        public class QuoteResponse
        {
            public string ParcelId { get; set; }
            public List<ServiceLevel> ServiceLevels { get; set; }
            public string Result { get; set; }
        }
        public class ServiceLevel
        {
            public int ServiceLevelID { get; set; }
            public decimal ShippingCharge { get; set; }
            public string Duty { get; set; }
            public decimal Tax { get; set; }
            public decimal Insurance { get; set; }
            public decimal subtotal { get; set; }
            public string CompanyCurrency { get; set; }
            public decimal ShippingChargeCompanyCurrency { get; set; }
            public decimal DutyCompanyCurrency { get; set; }
            public decimal TaxCompanyCurrency { get; set; }
            public decimal InsuranceCompanyCurrency { get; set; }
            public decimal subtotalCompanyCurrency { get; set; }
            public decimal PromoDiscount { get; set; }
            public decimal PromoDiscountCompanyCurrency { get; set; }
        }
        #endregion
    }
}
        

Submit Parcel

C♯

using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace i_parcelAPIConsumer
{
    class Program
    {
        static void Main(string[] args)
        {

            ParcelRequest parcelRequest = new ParcelRequest();
            parcelRequest.key = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE";

            parcelRequest.ItemDetailsList = new List<ItemDetails>();
            parcelRequest.ItemDetailsList.Add(new ItemDetails()
            {
                SKU = "SKUCODE",
                Quantity = 10,
            });

            parcelRequest.AddressInfo = new AddressInfo();
            parcelRequest.AddressInfo.Shipping = new Address()
            {
                FirstName = "TEST",
                LastName = "TEST",
                Street1 = "Test Road 1",
                Street2 = "Test Road 2",
                City = "Prospect",
                PostCode = "11111",
                Region = "NW",
                CountryCode = "AU",
                Email = "test@test.com",
                Phone = "111-111-1111"
            };
            parcelRequest.AddressInfo.Billing = new Address()
            {
                FirstName = "TEST",
                LastName = "TEST",
                Street1 = "Test Road 1",
                Street2 = "Test Road 2",
                City = "Prospect",
                PostCode = "11111",
                Region = "NW",
                CountryCode = "AU",
                Email = "test@test.com",
                Phone = "111-111-1111"
            };

            parcelRequest.OrderReference = "Order Reference";
            parcelRequest.DDP = true;

            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Encoding = Encoding.UTF8;
                client.BaseAddress = "https://webservices.i-parcel.com/";

                var request = new JavaScriptSerializer().Serialize(parcelRequest);
                var response = "";
                try
                {
                    response = client.UploadString(client.BaseAddress + "api/SubmitParcel", "POST", request);

                    var parcelResponse = new JavaScriptSerializer().Deserialize<ParcelResponse>(response);
                    //Process response
                }
                catch (Exception ex)
                {
                    //Handle Exception
                }
            }

        }

        #region Request Classes

        public class ParcelRequest
        {
            public string key { get; set; }
            public List<ItemDetails> ItemDetailsList { get; set; }

            public AddressInfo AddressInfo { get; set; }

            public string OrderReference { get; set; }
            public bool DDP { get; set; }

            public decimal OtherDiscount { get; set; }

            public string OtherDiscountCurrency { get; set; }

            public string PromoCode { get; set; }

        }
        public class ItemDetails
        {
            public string SKU { get; set; }
            public int Quantity { get; set; }
        }
        public class AddressInfo
        {
            public Address Shipping { get; set; }

            public Address Billing { get; set; }

        }
        public class Address
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Street1 { get; set; }
            public string Street2 { get; set; }
            public string PostCode { get; set; }
            public string City { get; set; }
            public string Region { get; set; }
            public string CountryCode { get; set; }
            public string Email { get; set; }
            public string Phone { get; set; }
        }
        #endregion

        #region Response Classes

        public class ParcelResponse
        {
            public string ParcelId { get; set; }

            public List<List<ServiceLevel>> ServiceLevels { get; set; }

            public string CarrierTrackingNumber { get; set; }
            public string Result { get; set; }
        }
        public class ServiceLevel
        {
            public int ServiceLevelID { get; set; }
            public decimal ShippingCharge { get; set; }
            public string Duty { get; set; }
            public decimal Tax { get; set; }
            public decimal Insurance { get; set; }
            public decimal subtotal { get; set; }
            public string CompanyCurrency { get; set; }
            public decimal ShippingChargeCompanyCurrency { get; set; }
            public decimal DutyCompanyCurrency { get; set; }
            public decimal TaxCompanyCurrency { get; set; }
            public decimal InsuranceCompanyCurrency { get; set; }
            public decimal subtotalCompanyCurrency { get; set; }
            public decimal PromoDiscount { get; set; }
            public decimal PromoDiscountCompanyCurrency { get; set; }
        }

        #endregion
    }
}