Simon Miller Team : Web Development Tags : Web Development

Australia Post API

Simon Miller Team : Web Development Tags : Web Development

From time to time in web development, we need to provide users with a simple way to select their suburb and/or postcode and pre-empt their choices with a type-ahead search. There are a few ways of achieving this – mostly involving storing our own database of every suburb and postcode in the country – but it now appears that Australia Post offers a free REST API, and have done so for at least a year.

The implementation is extremely simple, but contains one or two ‘gotchas’ worth mentioning. Here is a step by step guide as to how to get a free suburb/postcode lookup on your site: 

  1. Go to http://auspost.com.au/devcentre/pacpcs.asp and register for an Australia Post account
  2. Part of the registration process is to generate an API Key. You will receive the key in your email. This is required for all calls to the API.
  3. Read the technical implementation document: http://auspost.com.au/devcentre/assets/pdfs/pac-pcs-technical-specification.pdfYou can do far more with this API than just look up suburbs and postcodes, including determining Australia Post shipping charges for parcels.
  4. Your first thought may be to do the whole thing in jQuery. Unfortunately being an external API, browsers will see this as a cross-site scripting attack and deny the requests. For this to work, you will need to make a local handler.

The site I worked on was an Umbraco site, therefore was in Web Forms. If you are writing an MVC site, replace the handler with a method in one of your controllers and swap out the ‘context’ attribute for the attributes passed in the ‘data’ block in the jQuery below (that is, ‘excludePostBoxFlag’ and ‘q’) and return an action result of Json().

5. Now create the jQuery code to call the new handler. This code uses jQuery’s .autocomplete() function along with .ajax()

 

 

The API can return JSON or XML, but in this instance we want JSON. XML would be useful if you were doing pure server-side code as you could use Linq-to-XML to parse the result set. 

The API also returns more values than just ‘location’ and ‘postcode’, including ‘latitude’, ‘longitude’ and ‘state’.

6. And the final result! It has been suggested that you could enhance this by caching each search term in a local database and querying that before querying the API. This would definitely speed things up, but you would want to manage the size this database would reach.