Up and running with the Auspost Postcode API using PHP and jQuery autocomplete

What is Auspost API?

If you are a web developer working in Australia, at some point in your career, you will come across the need to validate  postcodes or suburbs. If you are specifically developing an ecommerce solution, you will also be interested in calculating postage costs in real-time. The Auspost API lets you do all of that.

In this article, I will cover validating Australian postcodes using the Auspost API.

1. Get an API key

The first thing you have to do is to get an Auspost API key. You can get it for free here. Once you have filled out the form, you will receive the API key by email.

auspost-key-email

2. Understand workflow

I will be using PHP for server side coding. You can use any language to complete this task. Project flow goes something like this:

  1. We will start typing in the suburb name or postcode in an input field.
  2. jQuery autocomplete will pickup our input and make an AJAX post request to our PHP script.
  3. The PHP script will receive the post data and send it off to the Auspost API as an HTTP request using PHP cURL*.
  4. The API will respond with XML or JSON data (we will be using JSON in this example).
  5. The JSON response will be printed so it can be fed back to jQuery autocomplete to populate type ahead.

*Make sure cURL extension is active in your PHP setup

3. Lets build our project

We will be creating two files for this task (you can name them anything you like):

  1. index.php (frontend)
  2. auspost.php (server side)

Our first iteration of the project will simply post data to the PHP script to see how the responses are coming. This will help us understand what is happening. This is also helpful if you don’t want AJAX autocomplete in your project 🙂

<html lang="en">
<head>
<meta charset="utf-8">
<title>Auspost Postcode search</title>
</head>
<body>
<form action="auspost.php" method="post">
<label for="postcode">Postcode:
<input name="postcode" id="postcode" type="text">
</label>
<input type="submit" value="submit" />
</form>
</body>
</html>

This is what it will end up looking like:

auspost-front-end

The PHP file looks something like this (don’t forget to paste in your API key):

<?php
//get post data. urlencode the postcode data incase someone enters a suburb name with spaces.
$postcode = urlencode($_POST['postcode']);
//your Auspost API
$apiKey = 'paste the API key here';
// Set the URL for the Postcode search
$urlPrefix = 'auspost.com.au';
$parcelTypesURL = 'http://' . $urlPrefix . '/api/postcode/search.json?q='.$postcode.'&excludePostBoxFlag=true';
// Lookup postcode
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $parcelTypesURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('AUTH-KEY: ' . $apiKey));
$rawBody = curl_exec($ch);
// Check the response: if the body is empty then an error occurred
if(!$rawBody){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
} else {
print_r($rawBody);
}
?>

4. Test our code

Type in the name or postcode of an Australian suburb and hit submit. If you have not made any mistakes, you should see a JSON response. It will not look nicely formatted like in the screenshot below because I am using a JSON formatter Chrome extension. Don’t worry, this has nothing to do with our task. Just make sure you are getting a valid  JSON response.

auspost-json

If you don’t want the autocomplete functionality, this is all you need to know about the postcode API. Interested in autocomplete? Keep reading …

5. Using jQuery autocomplete

To use autocomplete, we need to bring in jQuery and autocomplete JS libraries. The good news is that we don’t need to touch the PHP script anymore, its already all set! Here is our updated front-end code:

<html lang="en">
<head>
<meta charset="utf-8">
<title>Auspost Postcode search</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script>
$(function() {
$("#postcode").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'auspost.php', //your server side script
dataType: 'json',
data: {
postcode: request.term
},
success: function (data) {
//if multiple results are returned
if(data.localities.locality instanceof Array)
response ($.map(data.localities.locality, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
//if a single result is returned
else
response ($.map(data.localities, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
}
});
}
});
});
</script>
</head>
<body>
<form action="auspost.php" method="post">
<label for="postcode">Postcode:
<input name="postcode" id="postcode" type="text">
</label>
<input type="submit" value="submit" />
</form>
</body>
</html>

Now lets take it for a ride. Start typing a postcode/suburb. You should get something like this:

auspost-autocomplete

Note that I have kept the input field inside the form element with a submit button . You can get rid of everything but the input field and it should still work.

Wrapping up

I would like to refer to a few resources that helped me with the API:

I would also like to thank Simon Miller for his Auspost jQuery autocomplete example.