Masterfile and Transit Times Webservice

This is a RESTful web API service from TNT Swiss Post AG. The service validates the given information with the TNT location and service capabilities database (LMF) and response with the available TNT service codes. On a valid request, the service stores the user id and the date and time of the request for further analyzing purposes.

Service Authentication

The security of the service is based on HMAC SHA256 (Hash-Based-Message Authentication). Each call to the service needs to include a calculated HMAC key (URL Parameter). The key consists of 2 strings. The users userid and the hashed url. Following an example of a url call to the service. The HMAC message is added to the url by using the Auth= url parameter. The key itself contains the userid and the hashed key separated by a : /webservice.tnt.ch/api/countrylist/?Auth=userid:hashedKey

Example Url:

/webservice.tnt.ch/api/countrylist/?Auth=83D81CF4523645C23737D02961E3C5FAC8BD521D29D10E2ED959B45B2E6AA619:DMCH9wlBg6xaqDYqiA9US0EgeD0ENKr8OwJaTJMbiso=
				

Key Calculation

To calculate the HMAC key you will receive from us a userid and a secret.

Example
UserID: 83D81CF4523645C23737D02961E3C5FAC8BD521D29D10E2ED959B45B2E6AA619 Secret: 53CB18660B73B6081798C994A08B16D5672EDAA4
The full request URL has to be hashed. In the above example the following string /webservice.tnt.ch/api/countrylist/ is hashed. Do not hash the ?Auth=Userid:Key

Code Examples

Javascript

This example uses the CryptoJS library files Scripts/enc-base64-min.js and Scripts/enc-base64-min.js. The files are available 6192183425

function CalcHMAC(hashUrl) {
  var hmac = CryptoJS.HmacSHA256(hashUrl, PublicKey);
  var result = CryptoJS.enc.Base64.stringify(hmac);
  return result;
};
				

C#

This example is using the System.Security.Cryptography namespace.

private static string ComputeHash(string UrlString)
{
  var key = Encoding.UTF8.GetBytes(PublicKey.ToUpper());
  string hashString;
  using (HMACSHA256 hmac=new HMACSHA256(key))
  {
    var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(UrlString));
    hashString = Convert.ToBase64String(hash);
  }
  return hashString;
}  
				

Hashkey calculator

Calculator You will receive an example url based on the function to retreive a country list.

Your calculated url is:


				

Data Formats

The webservice is able to return the results in XML or JSON format. As default the servcie sends XML back to the calling application. You can retreive the results as JSON string by adding the parameter format=json to the url you call.

XML Example

<ArrayOfCountry xmlns:i="/www.w3.org/2001/XMLSchema-instance" xmlns="/schemas.datacontract.org/2004/07/LMF_TT.Models">
  <Country>
    <CountryCode>AD</CountryCode>
    <CountryName>ANDORRA</CountryName>
    <PostalCodes>Y</PostalCodes>
    <Regex>^(AD)\x20{0,1}\d{3}$</Regex>
    <EuClearance>false</EuClearance>
  </Country>
  <Country>
    <CountryCode>AE</CountryCode>
    <CountryName>UNITED ARAB EMIRATES</CountryName>
    <PostalCodes>N</PostalCodes>
    <Regex>^((\x20)|(\.)|(\-)){0,1}$</Regex>
    <EuClearance>false</EuClearance>
  </Country>
  <Country>
    <CountryCode>AF</CountryCode>
    <CountryName>AFGHANISTAN</CountryName>
    <PostalCodes>N</PostalCodes>
    <Regex>^((\x20)|(\.)|(\-)){0,1}$</Regex>
    <EuClearance>false</EuClearance>
  </Country>
  <Country>
    <CountryCode>AG</CountryCode>
    <CountryName>ANTIGUA AND BARBUDA</CountryName>
    <PostalCodes>N</PostalCodes>
    <Regex>^((\x20)|(\.)|(\-)){0,1}$</Regex>
    <EuClearance>false</EuClearance>
  </Country>
</ArrayOfCountry>

JSON Example

[
  {
    countryCode: "AD",
    countryName: "ANDORRA",
    euClearance: "False",
    postalCodes: "Y",
    regex: "^(AD)\x20{0,1}\d{3}$"
  },
  {
    countryCode: "AE",
    countryName: "UNITED ARAB EMIRATES",
    euClearance: "False",
    postalCodes: "N",
    regex: "^((\x20)|(\.)|(\-)){0,1}$"
  },
  {
    countryCode: "AF",
    countryName: "AFGHANISTAN",
    euClearance: "False",
    postalCodes: "N",
    regex: "^((\x20)|(\.)|(\-)){0,1}$"
  },
  {
    countryCode: "AG",
    countryName: "ANTIGUA AND BARBUDA",
    euClearance: "False",
    postalCodes: "N",
    regex: "^((\x20)|(\.)|(\-)){0,1}$"
  }
]

Service Methods

This section explains the available methods and the parameters to be passed.

getcountries

Description

This method returns a list of all available countries.

Service Url

/webservice.tnt.ch/api/countrylist/?format={format}&Auth={userid:HMACKey}

Parameters

Following parameters are available

Parameter Value Mandatory Description
format JSON/XML No This parameter specifies how the answer of the webservice is formatted. Valid values are XML and JSON. If the parameter is not sent the service will return XML.
Auth Userid:HMAC Yes Userid and HMAC Key separated by a :

Return Values

The answer of the service includes the following information.

Value Example Description
countryCode AD ISO Code of the Country
countryName Andorra Name of the Country
postalCodes Y Indicates if the country has postal codes. Possible Values: Y or N
regex ^(AD)\x20{0,1}\d{3}$ Regex validation string for postal codes.
euClearance true Indicates that euClearance is possible for this country. Possible Values: true or false

getcountry by country code

Description

This method returns one country.

Service Url

/webservice.tnt.ch/api/countrylist/?format={format}&countrycode={country_code}&Auth={userid:HMACKey}

Parameters

Following parameters are available

Parameter Value Mandatory Description
format JSON/XML No This parameter specifies how the answer of the webservice is formatted. Valid values are XML and JSON. If the parameter is not sent the service will return XML.
countrycode e.g. IT Yes 2 letter ISO country code
Auth Userid:HMAC Yes Userid and HMAC Key separated by a :

Return Values

The answer of the service includes the following information.

Value Example Description
countryCode AD ISO Code of the Country
countryName Andorra Name of the Country
postalCodes Y Indicates if the country has postal codes. Possible Values: Y or N
regex ^(AD)\x20{0,1}\d{3}$ Regex validation string for postal codes.
euClearance true Indicates that euClearance is possible for this country. Possible Values: true or false

lmfbypostalcode

Description

This method returns a list of all towns available for a postal code.

Service Url

/webservice.tnt.ch/api/lmfbypostalcode/?countrycode={country_code}&postalcode={zip_code}&format={format}&Auth={userid:HMACKey}

Parameters

Following parameters are available

Parameter Value Mandatory Description
countrycode e.g. IT Yes 2 letter ISO country code
postalcode e.g 87055 Yes Postalcode the system will search for
format JSON/XML No This parameter specifies how the answer of the webservice is formatted. Valid values are XML and JSON. If the parameter is not sent the service will return XML.
Auth Userid:HMAC Yes Userid and HMAC Key separated by a :

Return Values

The answer of the service includes the following information.

Value Example Description
townName MONTE OLIVETO Town Name
countryCode IT Name of the country
postCodeFrom 87055 Postcode range from
postCodeTo 87055 Postcode range to
zone D TNT Zone the postcode is in

lmfbytownname

Description

This method returns a list of all towns available for a passed town name. The query runs with Like %searchparam%. ara would find Aarau.

Service Url

/webservice.tnt.ch/api/lmfbytownname/?countrycode={country_code}&townname={town_name}&format={format}&Auth={userid:HMACKey}

Parameters

Following parameters are available

Parameter Value Mandatory Description
countrycode e.g. CH Yes 2 letter ISO country code
townname e.g ara Yes Part of the town name the system will search for.
format JSON/XML No This parameter specifies how the answer of the webservice is formatted. Valid values are XML and JSON. If the parameter is not sent the service will return XML.
Auth Userid:HMAC Yes Userid and HMAC Key separated by a :

Return Values

The answer of the service includes the following information.

Value Example Description
townName AARAU Town Name
countryCode CH Name of the country
postCodeFrom 5000 Postcode range from
postCodeTo 5000 Postcode range to
zone X TNT Zone the postcode is in

transittimes

Description

This method returns a list of all possible service codes including transit times for a given origin and destination.

Service Url

/webservice.tnt.ch/api/transittimes/?origincountry=#{origin_country_code}&originpostalcode=#{origin_zip}&origintownname=#{origin_town_name}&collectiondate=#{collectiondate}&collectiontime=#{collectiontime}&contype=#{contype}&destinationcountrycode=#{destination_country_code}&destinationpostalcode=#{destination_zip}&destinationtownname=#{destination_town_name}&euclearance=#{euclearance}&format={format}&Auth={userid:HMACKey}

Parameters

Following parameters are available

Parameter Value Mandatory Description
origincountry e.g. CH Yes 2 letter ISO code of the origin country
originpostalcode e.g 5000 No Postal Code if the country has postal codes. Required if country has postal codes
origintownname e.g Aarau Yes Name of the origin town
collectiondate 19.12.2012 Yes Date of collection
collectiontime 14:00 Yes Time of collection
contype D or N Yes D for documents, N for non-documents
destinationcountrycode DE Yes 2 letter ISO code of the destination country
destinationpostalcode 10001 No Destination postal code if the country has postal codes. Required if country has postal codes
destinationtownname e.g Berlin Yes Name of the destination town
euclearance True or False No True to return transit times for EU Clearance shipments
format JSON/XML No This parameter specifies how the answer of the webservice is formatted. Valid values are XML and JSON. If the parameter is not sent the service will return XML.
Auth Userid:HMAC Yes Userid and HMAC Key separated by a :

Return Values

The answer of the service includes the following information.

Value Example Description
origin/countryCode CH Origin country ISO code
origin/postalCode 5024 Origin town postal code
origin/townName Kuettigen Origin town name
destination/{0}/countryCode DE Destination country ISO code
destination/{0}/postalCode 10011 Destination town postal code
destination/{0}/townName Berlin Destination town name
destination/{0}/services/{0}/service 15N TNT service code
destination/{0}/services/{0}/serviceDescription Express (Non Docs) TNT service code description
destination/{0}/services/{0}/deliveryTime 2013-02-08T18:00:00 Estimated time of delivery. Format: yyyy-MM-dd HH:mm:ss

{0} is array index there can be multiple results returned back with {1}, {2} and so on...

Error Messages

You will find the possible error messages in the next table, ordered by the different methods.

Method ErrorMessage Description
ALL The user has been locked, please call the TNT Helpdesk The user is locked and cannot request any data.
ALL Unauthorized user! Public Key or HMAC invalid, you can check your HMAC creation with the "Hashkey calculator.
ALL Error in service, please call the TNT Helpdesk The web service runs in an error. Please call TNT Helpdesk.
Get country by country code Not a valid countrycode The country code is not supported by TNT
Get lmf by post code The country has no postal codes The post code field in the request contains a post code, but the country does not support post codes
Get lmf by post code The postalcode format is invalid The post code does not meet the post-code-format of the country.
Get lmf by post code The postalcode does not exist in the database The post code cannot be found in the lmf database or there is no service from TNT.
Get lmf by post code or town name No countrycode submitted The country code field in the request contains no country code.
Get lmf by post code or town name The countrycode is invalid The country code in the request is not valid or there is no service from TNT.
Get lmf by town name The town name does not exist in the database The town name cannot be found in the lmf database or there is no service from TNT.
Get lmf by town name No town name submitted The town name field in the request is empty or missing.
Get transit times CollectionDate not valid The collection date is not a valid date format.
Get transit times CollectionTime not valid The collection time is not a valid time format.
Get transit times EUClearance not valid The EUClearance field contains an invalid value.
Get transit times No destination countrycode submitted The destination country code field in the request contains no country code.
Get transit times No origin countrycode submitted The origin country code field in the request contains no country code.
Get transit times The CollectionDate was in the past The collection date was in the past. The transit time cannot be calculated.
Get transit times The consignment type is not valid The consignment type can only be "d", "D", "n" or "N".
Get transit times The destination combination of post code and town name is invalid or not a service from TNT The destination combination of post code and town name is invalid or not a service from TNT.
Get transit times The destination country has no postal codes and requires a town name The destination town name field in the request is empty, but the country does not support post codes and requires a town name to identify the destination.
Get transit times The destination country has no postal codes The destination post code field in the request contains a post code, but the country does not support post codes.
Get transit times The destination country must be in European Union For EU clearance service, the destination country must be in the European Union and EU clearance must be activated for the country.
Get transit times The destination country requires postal codes The destination post code field in the request contains no post code. This field is required if the country uses post codes.
Get transit times The destination countrycode is invalid The destination country code in the request is not valid or there is no service from TNT.
Get transit times The destination postalcode does not exist in the database The destination post code cannot be found in the lmf database or there is no service from TNT.
Get transit times The destination postalcode format is invalid The destination post code does not meet the post-code-format of the country.
Get transit times The destination town name does not exist in the database The destination town name cannot be found in the lmf database or there is no service from TNT.
Get transit times The origin combination of post code and town name is invalid or not a service from TNT The origin combination of post code and town name is invalid or not a service from TNT.
Get transit times The origin country has no postal codes and requires a town name The origin town name field in the request is empty, but the country does not support post codes and requires a town name to identify the origin.
Get transit times The origin country has no postal codes The origin post code field in the request contains a post code, but the country does not support post codes.
Get transit times The origin country must be Switzerland (ch) For EU clearance service, the origin country must be Switzerland.
Get transit times The origin country requires postal codes The origin post code field in the request contains no post code. This field is required if the country uses post codes.
Get transit times The origin countrycode is invalid The origin country code in the request is not valid or there is no service from TNT.
Get transit times The origin postalcode does not exist in the database The origin post code cannot be found in the lmf database or there is no service from TNT.
Get transit times The origin postalcode format is invalid The origin post code does not meet the post-code-format of the country.
Get transit times The origin town name does not exist in the database The origin town name cannot be found in the lmf database or there is no service from TNT.
Get transit times The worldwide transit times service is temporarily unavailable The service is not available.
Help Page Generation of the demo URL produce an Error The web service fails. Please call TNT Helpdesk.

Code Examples

Below you will find some code examples on how to access the service. Please note that the mentionned userid and secret are not working. Please contact us if you need a userid and a secret to use the service. Code examples can be downloaded here

Javascript Example

This example shows how to get the country list and the LMF data by postal code. The crypto library can be downloaded 724-583-1460

<script src="Scripts/jquery-1.8.2.js"></script>
<script src="Scripts/core-min.js"></script>
<script src="Scripts/enc-base64-min.js"></script>
<script src="Scripts/hmac-sha256.js"></script>

<script type="text/javascript">
  var UserID='83D81CF4523645C23737D02961E3C5FAC8BD521D29D10E2ED959B45B2E6AA619';
  var PublicKey = '53CB18660B73B6081798C994A08B16D5672EDAA4';
  var BaseURL = '/webservice.tnt.ch/api/';
    
  /Get the list of countries
  $('#Button1').click(function () {
    $('#TextArea1').text('');
    var myQueryURL = BaseURL + 'countrylist/';
    var AuthHMAC = CalcHMAC(myQueryURL);
    LoadCountryList(AuthHMAC, myQueryURL);
  });
  /Get the lmf data
  $('#Button2').click(function () {
    $('#TextArea1').text('');
    var myQueryURL = BaseURL + 'lmfbypostalcode/?countrycode=it&postalcode=87011';
    var AuthHMAC = CalcHMAC(myQueryURL);
    GetTownByPostalcode(AuthHMAC, myQueryURL);
  });
  function LoadCountryList(hmac, queryURL) {
    $.ajax({
      url: queryURL + '?Auth=' + UserID + ':' + hmac,
      type: "GET",
      dataType: "jsonp",
      success: function (data) {
        $.each(data, function (index) {
          $('#TextArea1').append('Countrycode: ' + this.countryCode + '\n');
          $('#TextArea1').append('Country:     ' + this.countryName + '\n');
          $('#TextArea1').append('PostCodes:   ' + this.postalCodes + '\n');
          $('#TextArea1').append('RegEx:       ' + this.regex + '\n' + '\n');
        });
      },
      error: function (response) {
        $('#TextArea1').text(response);
      }
    });
  };

  function GetTownByPostalcode(hmac, queryUrl) {
    $.ajax({
      url: queryUrl + '&Auth=' + UserID + ':' + hmac,
      type: "GET",
      dataType: "jsonp",
      success: function (data) {
        if ($.isArray(data) && $.isPlainObject(data[0]))
        {
          for (var key in data)
          {
            for (var keyItem in data[key])
            {
              $('#TextArea1').append(keyItem + ' - > ' + data[key][keyItem] + '\n');
            }
          }
        }
        else {
          $('#TextArea1').append('\n' + data);
        }
      },
      error: function (response) {
        $('#TextArea1').text(response);
      }
    });
  };

  function CalcHMAC(hashUrl) {
    var hmac = CryptoJS.HmacSHA256(hashUrl, PublicKey);
    var result = CryptoJS.enc.Base64.stringify(hmac);
    return result;
  };
</script>

C# Example

This example shows how to get the country list and the LMF data by postal code. The json.net library can be downloaded here.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;

namespace TestClientCSharp
{
  class Program
  {
    private const string UserID = "83D81CF4523645C23737D02961E3C5FAC8BD521D29D10E2ED959B45B2E6AA619";
    private const string PublicKey = "53CB18660B73B6081798C994A08B16D5672EDAA4";
    private const string ClientURL = "/webservice.tnt.ch/api/";
   
    static void Main(string[] args)
    {
      TestCountryList_1(); /GetJSON
      TestCountryList_2(); /GetJSONandloopthroughdata
      TestLMFbyPostalCode();/Get JSON
      Console.Read();
    }
    
    private static void TestCountryList_1()
    {
      string apiAction = "countrylist/";
      string hmacHash = ComputeHash(apiAction);
      string urlString = string.Format("{0}?Auth={1}:{2}", ClientURL + apiAction, UserID, hmacHash);
      WebClient webClient = new WebClient();
      string result = webClient.DownloadString(urlString);
      Console.WriteLine(result);
    }

    private static void TestCountryList_2()
    {
      string apiAction = "countrylist/";
      string hmacHash = ComputeHash(apiAction);
      WebRequest request = WebRequest.Create(string.Format("{0}?Auth={1}:{2}", ClientURL + apiAction, UserID, hmacHash));
      using (var response = (HttpWebResponse)request.GetResponse())
      {
        var responseValue = string.Empty;
        using (var responseStream = response.GetResponseStream())
        {
          using (var reader = new StreamReader(responseStream))
          {
            JsonSerializer js = new JsonSerializer();
            var myType = typeof(List<Dictionary<string, string>>);
            List<Dictionary<string, string>> objJson = (List<Dictionary<string, string>>)js.Deserialize(reader, myType);

            foreach (var cItem in objJson)
            {
              foreach (var sItem in cItem)
              {
                Console.WriteLine(string.Format("{0}  -  {1}",sItem.Key,sItem.Value));
              }
            }
          }
        }
      }
    }

    private static void TestLMFbyPostalCode()
    {
      string apiAction = "lmfbypostalcode/";
      string query = "countrycode=it&postalcode=87011";
      string hmacHash = ComputeHash(string.Format("{0}?{1}", apiAction, query));
      string urlString = string.Format("{0}?{1}&Auth={2}:{3}", ClientURL + apiAction, query, UserID, hmacHash);
      WebClient webClient = new WebClient();
      string result = webClient.DownloadString(urlString);
      Console.WriteLine(result);
    }
   
    private static string ComputeHash(string addUrlString)
    {
      var key = Encoding.UTF8.GetBytes(PublicKey.ToUpper());
      string hashString;
      using (HMACSHA256 hmac=new HMACSHA256(key))
      {
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(ClientURL + addUrlString));
        hashString = Convert.ToBase64String(hash);
      }
      return hashString;
    }
  }
}