Introduction

The Postcode Evolution Service provides full access to the AFD API for all our products. The API is easy to use and quick to implement consisting entirely of GET requests and returned XML data, while balancing that with providing full flexibility. This enables you to rapidly develop using the API with practically any development environment to provide the data that you require. All AFD products provide rapid lookup and search functionality allowing you to implement address management solutions and provide bank data, account and card validation.

To make life as easy as possible, a Wizard which will generate sample projects and code for the major development environments is also available (see separate guide).

The API is also backed up by our free customer support services. You can visit our website at www.afd.co.uk/support for full developer support with using our API.

Getting Started

Using any standard environment and parse you can simply make GET requests to our service and retrieve XML.

We recommend that for the most rapid development and to help you know where to start that you use our API Wizard to generate a sample project for your development environment. If your environment is not one that is listed, then select one that is closest to your own and use that as a basis for your coding. By looking at a sample project you can get a look and feel for how the API works and what you can do with it and you can easily copy and paste the code from that into your own and adapt it to meet your needs. Our sample projects work in the way that your own application is most likely to work, but also keep code to an absolute minimum, whilst being well commented, so that you can transfer the code with ease. The API Wizard also provides the code to go into a module or class in your application with all our API declarations and constants included which you can copy and paste into your own application. The code for lookup and search functionality is also provided and can be similarly copied and pasted. See the separate documentation for that wizard.

API Reference for XML

Calling the PostcodeEvolution Server

All calls to the PostcodeEverywhere XML server follow the same basic structure. The parameters that make up each call to the server can either be specified as parameters in the URL string, separated by ampersands i.e. using GET functionality, or can be sent to the server as a POST. Note that in the case of Internet applications we strongly recommend that you have calls to the service running server-side with the code inaccessible to end-users to prevent abuse of the service, and in the case of the hosted service to protect your serial number and password.

The URL for PCE requests is SERVER + “/afddata.pce”.

For example:

http://pce.afd.co.uk/afddata.pce

would be our hosted server URL for Common-API requests.

The parameters usually supplied are then as follows:

Serial Your assigned serial number
Password Your assigned password
UserID Optional: Enables you to identify different users or systems when comparing requests to any logs you may hold.
Data Specifies the data you are using (see section 5.2.1 below)
Task Specifies the task to carry out (see section 5.2.2 below)
Fields: Specifies the fields to use (see section 5.2.3 below)
MaxQuantity Optional: Specifies the maximum number of records to return

These are then followed by function specific parameters, for example if you are carrying out a Lookup you would use the lookup parameter to specify the field to lookup.

The MaxQuantity settings are also optional, however if not specified a maximum quantity of 100 results will be assumed.

You should note that regardless of the maximum quantity setting there is a timeout setting (default 30 seconds) and a 128 kilobyte buffer limit for the server to retain server responsiveness and prevent buffer overflows. This means that with large quantities of results or slow searches the number of results returned may be less than MaxQuantity. Postcode and WorldAddress also have upper limits of 300 and 1000 results respectively. If you are not obtaining the result you require you should refine your search to be more specific.

Your then load this XML document in your parser and should check for any error returned by the parser and deal with it appropriately (e.g. displaying the error to the user and aborting).

You can then read the required data from the records returned.

Regardless of the data or operation used, the XML structure will always be in the following format:

<AFDPostcodeEverywhere>
  <Result>1</Result>
  <ErrorText />
  <Item value = “1”>
      … fields returned
  </Item>
  …
</AFDPostcodeEverywhere>

Where:

  • Result is numeric and either contains an error (value less than 0) or the number of items returned (> 0).
  • ErrorText contains a description of the error which occurred if the value of Result is less than 0.
  • If the function is successful then the Result code returned is >= 0. The results are contained in Item nodes (this will be one or more if the operation was successful).

Lookup Function

The most commonly used function across our product range is the Lookup function. By entering a single string the user can find the results matching their lookup criteria.

To carry out a lookup you would pass a query string to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2. The only additional parameter needed is Lookup= which should be set to the lookup string to find.

If you are wishing to use International data then you will also need to add the &Country= or &CountryISO parameter (e.g. &CountryISO=FRA) to specify the country to use if it is not the UK (GBR).

For example, a valid lookup string for our hosted service to retrieve a list of matching results from an Address Management product would be:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Address&Task=FastFind&Fields=List&Lookup=B111AA

When using BankFinder you may wish to add the clearing system you wish to restrict records to as well. You can do this by adding the Clearing parameter to the string. Using Clearing=UK restricts records to those on the UK (BACS) clearing system only. Using Clearing=Irish restricts records to those on the Irish (IPSO) clearing system only. If you can only clear through the UK system it is important to include the Clearing=UK parameter, for example:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Bank&Clearing=UK&Task=FastFind&Fields=List&Lookup=050246

An example string to retrieve a nearest result using AFD Nearest functionality would be:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Nearest&Task=FastFind&Fields=List& DBConnect=MyDB&MaxQuantity=20&Miles=200&Lookup=B111AA

If an error occurs the Result field returned will be set to a value less than zero and the ErrorText will contain a corresponding error message.

In the case of Address Management products the PostcodeFrom field returned in each XML item will be set if a postcode was looked up which has changed following a Royal Mail recoding. The lookup will complete using the new postcode (found in the Postcode field), however you may wish to display a message notifying the user of this.

Assuming no error occurred, you can then either add each result to a list box (using Field=List would reduce the size of the XML returned in this case), or process each result in full.

' Example VB Code for carrying out an Address Management lookup
' Declare XML Objects and variables
Dim xmlDoc As Object
Dim root As Object
Dim pcFromNode As Object
Dim dataNode As Object
Dim itemNodes As Object
Dim listNode As Object
Dim keyNode As Object
Dim xmlLocation As String
' Initialise the Microsoft XML Document Object Model
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Replace lstResult with the name of your list box for the results
With lstResult
' Clear out any existing items in the list
.Clear
' Build up the XML query string
xmlLocation = AFD_SERVER + "/afddata.pce?"
xmlLocation = xmlLocation + "Serial=" + AFD_SERIAL_NUMBER + "&"
xmlLocation = xmlLocation + "Password=" + AFD_PASSWORD + "&"
xmlLocation = xmlLocation + "UserID=" + AFD_USER_ID + "&"
xmlLocation = xmlLocation + "Data=Address&Task=FastFind&Fields=List"
' Set the maximum number of records to return
xmlLocation = xmlLocation + "&MaxQuantity=100"
' Set the lookup string
xmlLocation = xmlLocation + "&Lookup=" + txtLookup.Text ' Change txtLookup to your lookup entry textbox
' Load the XML from the webserver with the query string
xmlDoc.Load (xmlLocation)
' Check for any XML Parser error
If xmlDoc.parseError.errorCode < 0 Then
  Msgbox "Error: " & xmlDoc.parseError.reason & vbCrLf & "Microsoft.XMLDOM Error Code: " & Str(xmlDoc.parseError.errorCode)
  Exit Sub
End If
' Check if PCE returned an error and if the document is valid
Set root = xmlDoc.documentElement
Set dataNode = root.selectSingleNode("Result")
Set itemNodes = root.selectNodes("Item")
If dataNode Is Nothing or itemNodes Is Nothing Then
  Msgbox "Invalid PCE XML Document"
  Exit Sub
End If
If Val(dataNode.Text) < 1 Then
  Set dataNode = root.selectSingleNode("ErrorText")
  If dataNode Is Nothing Then
    Msgbox "Invalid PCE XML Document"
  Else
    Msgbox dataNode.Text ' Show the user the error
  End If
  Exit Sub
End If
' Display any changed postcode if applicable
Set pcFromNode = itemNodes(0).selectSingleNode("PostcodeFrom")
Set dataNode = itemNodes(0).selectSingleNode("Postcode")
If Not (pcFromNode Is Nothing) and Not (dataNode Is Nothing) Then
  If pcFromNode.Text <> "" Then
    MsgBox "Postcode has changed from " + pcFromNode.Text + " to " + dataNode.Text
  End If
End If
' Now add matching records to the list box
For Each dataNode In itemNodes
    ' Get the data nodes
    Set listNode = dataNode.selectSingleNode("List")
    Set keyNode = dataNode.selectSingleNode("Key")
      If Not (listNode Is Nothing) And Not (keyNode Is Nothing) Then
      ' Add the item to the list box with hidden key at the end
      .AddItem listNode.Text + Space(512) + keyNode.Text
    End If
Next
If .ListCount <> 0 Then .ListIndex = 0 ' Select First item in the list
End With

Search Function

The search function allows records to be located by searching using specific fields rather than a general lookup string. It allows any of the Fields to be searched that are specified as being searchable for the AFD product that you are using in Appendix A (for Address Management products) or Appendix B (for BankFinder). In the case of Nearest any field in your database can be searched for.

To carry out a search you would pass a query string to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2. You should add a parameter for each field that you wish to search on.

If you are wishing to use International data then you will also need to add the &Country= or &CountryISO parameter (e.g. &CountryISO=FRA) to specify the country to use if it is not the UK (GBR).

For example, a valid lookup string for our hosted service to retrieve a list of matching results for a search for Commercial Street in the street field and Birmingham in the town field from an Address Management product would be:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Address&Task=Search&Fields=List&Street=Commercial%20Street&Town=Birmingham

When using BankFinder you may wish to add the clearing system you wish to restrict records to as well. You can do this by adding the Clearing parameter to the string. Using Clearing=UK restricts records to those on the UK (BACS) clearing system only. Using Clearing=Irish restricts records to those on the Irish (IPSO) clearing system only. If you can only clear through the UK system it is important to include the Clearing=UK parameter, for example:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Bank&Clearing=UK&Task=Search&Fields=List&OwnerBankFullName=Natwest&Town=Birmingham

If an error occurs the Result field returned will be set to a value less than zero and the ErrorText will contain a corresponding error message.

Assuming no error occurred, you can then either add each result to a list box (using Field=List would reduce the size of the XML returned in this case), or process each result in full.

' Example VB code for an Address Management Search:
' Declare XML Objects and variables
Dim xmlDoc As Object
Dim root As Object
Dim pcFromNode As Object
Dim dataNode As Object
Dim itemNodes As Object
Dim listNode As Object
Dim keyNode As Object
Dim xmlLocation As String
' Initialise the Microsoft XML Document Object Model
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Replace lstResult with the name of your list box for the results
With lstResult
' Clear out any existing items in the list
.Clear
' Build up the XML query string
xmlLocation = AFD_SERVER + "/afddata.pce?"
xmlLocation = xmlLocation + "Serial=" + AFD_SERIAL_NUMBER + "&"
xmlLocation = xmlLocation + "Password=" + AFD_PASSWORD + "&"
xmlLocation = xmlLocation + "UserID=" + AFD_USER_ID + "&"
xmlLocation = xmlLocation + "Data=Address&Task=Search&Fields=List"
' Set the maximum number of records to return
xmlLocation = xmlLocation + "&MaxQuantity=100"
' Set the parameters to search on
xmlLocation = xmlLocation + "&Organisation=" + txtSearchOrganisation.Text
xmlLocation = xmlLocation + "&Property=" + txtSearchProperty.Text
xmlLocation = xmlLocation + "&Street=" + txtSearchStreet.Text
xmlLocation = xmlLocation + "&Locality=" + txtSearchLocality.Text
xmlLocation = xmlLocation + "&Town=" + txtSearchTown.Text
xmlLocation = xmlLocation + "&Postcode=" + txtSearchPostcode.Text
' Load the XML from the webserver with the query string
xmlDoc.Load (xmlLocation)
' Check for any XML Parser error
If xmlDoc.parseError.errorCode < 0 Then
    Msgbox "Error: " & xmlDoc.parseError.reason & vbCrLf & "Microsoft.XMLDOM Error Code: " & Str(xmlDoc.parseError.errorCode)
    Exit Sub
End If
' Check if PCE returned an error and if the document is valid
Set root = xmlDoc.documentElement
Set dataNode = root.selectSingleNode("Result")
Set itemNodes = root.selectNodes("Item")
If dataNode Is Nothing or itemNodes Is Nothing Then
    Msgbox "Invalid PCE XML Document"
    Exit Sub
End If
If Val(dataNode.Text) < 1 Then
    Set dataNode = root.selectSingleNode("ErrorText")
    If dataNode Is Nothing Then
        Msgbox "Invalid PCE XML Document"
    Else
        Msgbox dataNode.Text ' Show the user the error
    End If
    Exit Sub
End If
' Now add matching records to the list box
For Each dataNode In itemNodes
    ' Get the data nodes
    Set listNode = dataNode.selectSingleNode("List")
    Set keyNode = dataNode.selectSingleNode("Key")
    If Not (listNode Is Nothing) And Not (keyNode Is Nothing) Then
        ' Add the item to the list box with hidden key at the end
        .AddItem listNode.Text + Space(512) + keyNode.Text
    End If
    Next
    If .ListCount <> 0 Then .ListIndex = 0 ' Select First item in the list
End With

Retrieve Function

If you have added items to a list retrieving own the List and Key items you will want to re-retrieve a result should the user click on it. To retrieve the record they select you should use the Key Field which will have been returned with each result, and which you should have stored with the list items.

To fetch the record you would pass a query string to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2 using the Retrieve Task. The only additional parameter needed is Key= which should be set to the key field which was returned for the item.

If you are wishing to use International data then you will also need to add the &Country= or &CountryISO parameter (e.g. &CountryISO=FRA) to specify the country to use if it is not the UK (GBR).

For example, if you had retrieved a result with a key of B111AA1001 then a valid lookup string for our hosted service to retrieve the full result from an Address Management product would be:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Address&Task=Retrieve&Fields=Standard&Key=B111AA1001

If an error occurs (e.g. the key supplied was invalid) the Result field returned will be set to a value less than zero and the ErrorText will contain a corresponding error message, otherwise you will now have the record fields in the XML.

Note that only one item will ever be returned from a Retrieve Task as you are requesting a single item, by its key, which was earlier returned in a list.

' Example VB code to fetch an item selected in the list for Address Management products:
' Declare XML Objects and variables
Dim xmlDoc As Object
Dim root As Object
Dim pcFromNode As Object
Dim dataNode As Object
Dim itemNodes As Object
Dim xmlLocation As String
' Initialise the Microsoft XML Document Object Model
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Build up the XML query string
xmlLocation = AFD_SERVER + "/afddata.pce?"
xmlLocation = xmlLocation + "Serial=" + AFD_SERIAL_NUMBER + "&"
xmlLocation = xmlLocation + "Password=" + AFD_PASSWORD + "&"
xmlLocation = xmlLocation + "UserID=" + AFD_USER_ID + "&"
xmlLocation = xmlLocation + "Data=Address&Task=Retrieve&Fields=Standard"
' Set the maximum number of records to return
xmlLocation = xmlLocation + "&MaxQuantity=100"
' Replace lstResult with the name of your list box for the results
With lstResult
    ' Check a valid item is selected
    If .ListIndex = -1 Then
        Msgbox "No Item Selected"
        Exit Sub
    End If
    ' Set XML parameter to retrieve the selected record
    xmlLocation = xmlLocation + "&Key=" + Trim(Right(lstResult, 40)) ' Replace lstResult with the name of your list box for the results
    ' Finished with the list box
End With
' Load the XML from the webserver with the query string
xmlDoc.Load (xmlLocation)
' Check for any XML Parser error
If xmlDoc.parseError.errorCode < 0 Then
    Msgbox "Error: " & xmlDoc.parseError.reason & vbCrLf & "Microsoft.XMLDOM Error Code: " & Str(xmlDoc.parseError.errorCode)
    Exit Sub
End If
' Check if PCE returned an error and if the document is valid
Set root = xmlDoc.documentElement
Set dataNode = root.selectSingleNode("Result")
Set itemNodes = root.selectNodes("Item")
If dataNode Is Nothing or itemNodes Is Nothing Then
    Msgbox "Invalid PCE XML Document"
    Exit Sub
End If
If Val(dataNode.Text) < 1 Then
    Set dataNode = root.selectSingleNode("ErrorText")
    If dataNode Is Nothing Then
        Msgbox "Invalid PCE XML Document"
    Else
        Msgbox dataNode.Text ' Show the user the error
    End If
    Exit Sub
End If
' Now Assign required fields to your application (only one will be returned)
Set dataNode = itemNodes(0).selectSingleNode("Name")
If Not (dataNode Is Nothing) Then txtName.Text = dataNode.Text
    Set dataNode = itemNodes(0).selectSingleNode("Organisation")
If Not (dataNode Is Nothing) Then txtOrganisation.Text = dataNode.Text
    Set dataNode = itemNodes(0).selectSingleNode("Property")
If Not (dataNode Is Nothing) Then txtProperty.Text = dataNode.Text
 	Set dataNode = itemNodes(0).selectSingleNode("Street")
If Not (dataNode Is Nothing) Then txtStreet.Text = dataNode.Text
    Set dataNode = itemNodes(0).selectSingleNode("Locality")
If Not (dataNode Is Nothing) Then txtLocality.Text = dataNode.Text
    Set dataNode = itemNodes(0).selectSingleNode("Town")
If Not (dataNode Is Nothing) Then txtTown.Text = dataNode.Text
    Set dataNode = itemNodes(0).selectSingleNode("Postcode")
 If Not (dataNode Is Nothing) Then txtPostcode.Text = dataNode.Text

Account Number Validation – BankFinder Only

This function provides the ability to validate a sort code and account number. This checks that the account number is valid for the branch of the bank which the sortcode belongs to. This does not guarantee that the account number exists or sufficient funds exist for any transaction, but greatly cuts down on errors due to incorrectly entered numbers. The function will also translate any non-standard account numbers (e.g. a 10-digit account number).

To carry out a validation you would pass a query string to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2. You should supply a sortcode and account number as additional parameters (or instead the IBAN if validating an account number in that International standardised format).

For example, a valid lookup string for our hosted service to validate an account number 24782346 on sort code 774814 would be as follows:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Bank&Task=Account&Fields=Account&SortCode=774814&AccountNumber=24782346

You may wish to add the clearing system you wish to restrict records to as well. You can do this by adding the Clearing parameter to the string. Using Clearing=UK restricts records to those on the UK (BACS) clearing system only. Using Clearing=Irish restricts records to those on the Irish (IPSO) clearing system only. If you can only clear through the UK system it is important to include the Clearing=UK parameter, for example:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Bank&Clearing=UK&Task=Account&Fields=Account&SortCode=774814&AccountNumber=24782346

You can also supply a Roll Number in the case of crediting some building society accounts which require one which will also be checked.

If the account number is invalid, the Result field returned will be set to a value less than zero and the ErrorText will contain a corresponding error message.

Assuming no error occurred, you can assume the account number is valid, but should read the Sortcode, AccountNumber, IBAN and RollNumber (if required) and TypeOfAccount parameters in-case the number has been translated.

If the return value is AFD_SUCCESS (1) then the account number has been validated, if the return value is AFD_SUCCESS_NO_VALIDATION (2) then account numbers on this sortcode cannot be validated and so the number should still be treated as valid. This return code is provided so you can carry out an additional check on the account number, e.g. asking a customer on the phone to repeat it, checking it has been entered from a paper form correctly etc. if you wish to do so.

Note that the only Field type valid for validating account numbers is Standard as the result contains no address. Only a single result will ever be returned so there is no need to list results.

Should you also wish to check the branch details match those that the customer has supplied, check the transaction types allowed at this branch, or obtain the address to use for this branch (may not be the branch physical location) then you can carry out a lookup for the sortcode (see Section 5.3) to obtain the branch information.

' Example VB code to validate an account number:
' Declare XML Objects and variables
Dim xmlDoc As Object
Dim root As Object
Dim pcFromNode As Object
Dim dataNode As Object
Dim itemNodes As Object
Dim sortCodeNode As Object
Dim accountNode As Object
Dim typeOfAccountNode As Object
Dim clearingSystemNode As Object
Dim xmlLocation As String
' Initialise the Microsoft XML Document Object Model
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Build up the XML query string
xmlLocation = AFD_SERVER + "/afddata.pce?"
xmlLocation = xmlLocation + "Serial=" + AFD_SERIAL_NUMBER + "&"
xmlLocation = xmlLocation + "Password=" + AFD_PASSWORD + "&"
xmlLocation = xmlLocation + "UserID=" + AFD_USER_ID + "&"
xmlLocation = xmlLocation + "Data=Bank&Task=Account&Clearing=Both&Fields=Account"
' Set the Sort Code and Account Number
xmlLocation = xmlLocation + "&SortCode=" + txtValidateSortCode.Text ' Change txtValidateSortCode to your sortcode entry textbox
xmlLocation = xmlLocation + "&AccountNumber=" + txtValidateAccountNo.Text ' Change txtValidateAccountNo to your account number entry textbox
' Load the XML from the webserver with the query string
xmlDoc.Load (xmlLocation)
' Check for any XML Parser error
If xmlDoc.parseError.errorCode < 0 Then
    Msgbox "Error: " & xmlDoc.parseError.reason & vbCrLf & "Microsoft.XMLDOM Error Code: " & Str(xmlDoc.parseError.errorCode)
    Exit Sub
End If
' Check if PCE returned an error and if the document is valid
Set root = xmlDoc.documentElement
Set dataNode = root.selectSingleNode("Result")
Set itemNodes = root.selectNodes("Item")
If dataNode Is Nothing or itemNodes Is Nothing Then
    Msgbox "Invalid PCE XML Document"
    Exit Sub
End If
If Val(dataNode.Text) < 1 Then
    Set dataNode = root.selectSingleNode("ErrorText")
	If dataNode Is Nothing Then
	    Msgbox "Invalid PCE XML Document"
    Else
        Msgbox dataNode.Text ' Show the user the error
    End If
    Exit Sub
End If
' Display validation result - with details to submit for payment - note non-standard account number's will be translated
Set sortCodeNode = itemNodes(0).selectSingleNode("SortCode")
Set accountNode = itemNodes(0).selectSingleNode("AccountNumber")
Set typeOfAccountNode = itemNodes(0).selectSingleNode("TypeOfAccount")
Set clearingSystemNode = itemNodes(0).selectSingleNode("ClearingSystem")
If sortCodeNode Is Nothing Or accountNode is Nothing Or typeOfAccountNode Is Nothing Or clearingSystemNode is Nothing Then
    Msgbox "Invalid PCE XML Document"
Else
    MsgBox "Account Number Valid: " + vbCrLf + vbCrLf + "Sortcode: " + sortCodeNode.Text + vbCrLf + "Account Number: " + accountNode.Text + vbCrLf + "Type of Account Code: " + typeOfAccountNode.Text + vbCrLf + "Clearing System: " + clearingSystemNode.Text
End If

Card Number Validation – BankFinder Only

This function provides the ability to validate a card number, and optionally check that an expiry date indicates that the card is in-date. This checks that the card number is a valid one for the type of card and can indicate the card type. This does not guarantee that the card exists or that a transaction will be authorized, but greatly cuts down on errors due to incorrectly entered numbers.

To carry out a validation you would pass a query string to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2. You should supply a card number, and optionally expiry date, as additional parameters.

For example, a valid lookup string for our hosted service to validate a card number of 4903005748392742 with expiry date 01/10 would be as follows:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Bank&Task=Card&Fields=Card&CardNumber=4903005748392742&ExpiryDate=01/10

If the card number is invalid, the Result field returned will be set to a value less than zero and the ErrorText will contain a corresponding error message.

Assuming no error occurred, you can assume the card number is valid. If you wish to determine the card type, the CardType field will hold this information.

Note that the only Field type valid for validating card numbers is Standard as the result contains no address. Only a single result will ever be returned so there is no need to list results.

' Example VB code to validate a card number:
' Declare XML Objects and variables
Dim xmlDoc As Object
Dim root As Object
Dim pcFromNode As Object
Dim dataNode As Object
Dim itemNodes As Object
Dim xmlLocation As String
' Initialise the Microsoft XML Document Object Model
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Build up the XML query string
xmlLocation = AFD_SERVER + "/afddata.pce?"
xmlLocation = xmlLocation + "Serial=" + AFD_SERIAL_NUMBER + "&"
xmlLocation = xmlLocation + "Password=" + AFD_PASSWORD + "&"
xmlLocation = xmlLocation + "UserID=" + AFD_USER_ID + "&"
xmlLocation = xmlLocation + "Data=Bank&Task=Card&Fields=Card"
' Set the Card Number and Expiry Date (Optional)
xmlLocation = xmlLocation + "&CardNumber=" + txtValidateCardNo.Text ' Change txtValidateCardNo to your card number entry textbox
xmlLocation = xmlLocation + "&ExpiryDate=" + txtValidateExpiry.Text ' Change txtValidateExpiry to your expiry date entry textbox
' Load the XML from the webserver with the query string
xmlDoc.Load (xmlLocation)
' Check for any XML Parser error
If xmlDoc.parseError.errorCode < 0 Then
    Msgbox "Error: " & xmlDoc.parseError.reason & vbCrLf & "Microsoft.XMLDOM Error Code: " & Str(xmlDoc.parseError.errorCode)
    Exit Sub
End If
' Check if PCE returned an error and if the document is valid
Set root = xmlDoc.documentElement
Set dataNode = root.selectSingleNode("Result")
Set itemNodes = root.selectNodes("Item")
If dataNode Is Nothing or itemNodes Is Nothing Then
    Msgbox "Invalid PCE XML Document"
    Exit Sub
End If
If Val(dataNode.Text) < 1 Then
    Set dataNode = root.selectSingleNode("ErrorText")
    If dataNode Is Nothing Then
        Msgbox "Invalid PCE XML Document"
    Else
        Msgbox dataNode.Text ' Show the user the error
    End If
    Exit Sub
End If
' Display validation result
Set dataNode = itemNodes(0).selectSingleNode("CardType")
If dataNode Is Nothing Then
    Msgbox "Invalid PCE XML Document"
Else
    MsgBox "Card Valid: " + dataNode.Text
End If

List Functions – UK Address Management Only

With Postcode Plus, Names & Numbers and TraceMaster products you can use the list functions to obtain a list of alias localities for the postcode sector that a postcode or result is contained in. These are non-postally required localities held by Royal Mail which can or may be included on an address if desired. An example of this would be including Wimbledon for an address in London. You should note that these are stored at postal sector level (e.g. SW19 1) and there are often multiple entries for an address so a locality being returned does not mean it is necessarily the best one for the particular address you are viewing.

For Names & Numbers and TraceMaster products only it is also possible to obtain a list of possible values for most fields, e.g. all the Mailsort codes present, business descriptions, etc. You can also specify the start value of the field, e.g. return all surnames present starting with “Smith”.

When using International data you can also use the List functions to obtain a list of all available countries (names or ISO codes).

To carry out a lookup you would pass a query string to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2. The only additional parameter needed is Lookup= which should be set to the lookup string to find.

For example, a valid lookup string for our hosted service to retrieve a list of alias localities for the sector containing postcode B29 4AA would be:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=List&Task=ListAliasLocality&Fields=Standard&Lookup=B29 4AA

With Names & Numbers a string to return all possible values for the Size (of business) field would be:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=List&Task=ListSize&Fields=Standard&Lookup=

A string to return surnames starting Smith would be:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=List&Task=ListSurname&Fields=Standard&Lookup=Smith

If an error occurs the Result field returned will be set to a value less than zero and the ErrorText will contain a corresponding error message.

Assuming no error occurred, you can then process the results returned as desired.

' Example VB code for a List operation to retrieve alias localities:
Dim details As AFDListData
Dim retVal As Long
Static running As Boolean
' Prevent corruption of list box from button being clicked twice
If running Then Exit Sub
running = True
' Replace lstResult with the name of your list box for the results
With lstResult
' Clear out any existing items in the list
.Clear
' Reset Cancel flag
cancelFlag = False
' Set the lookup
details.Lookup = txtLookup.Text ' Change txtLookup to the postcode or record key you wish to lookup
' Carry out the lookup (Can alter the operation to retrieve N&N list items if desired)
retVal = AFDData(afdFieldSpec, AFD_LIST_ALIAS_LOCALITY, details)
' Abort with Message if error or user cancelled
If retVal < 0 Then
    MsgBox AFDErrorText(retVal)
    running = False
    Exit Sub
End If
' Now add matching records to the list box
Do While retVal >= 0
    ' Add the item to the list box with hidden key at the end
    .AddItem Trim(details.List)
    ' Give user the chance to cancel and allow list box to update
    DoEvents
    ' Check if user cancelled
    If cancelFlag Then
        MsgBox "Lookup Cancelled"
	    running = False
	    Exit Sub
    End If
    retVal = AFDData(afdFieldSpec, AFD_GET_NEXT + AFD_LIST_ALIAS_LOCALITY, details)
    Loop
    ' Check results have been returned
    If .ListCount = 0 Then
        MsgBox "No Results Found"
    Else
        .ListIndex = 0 ' Select First item in the list
    End If
End With
running = False
//Example C++ Code For an Address Management Lookup (Visual C++)
HINSTANCE afdDLL = (HINSTANCE)NULL;
AFDDATA afdData = (AFDDATA)NULL;
static bool running = false;
afdListData details;
char listItem[2055];
char msgTxt[255];
long retVal;
CListBox* listBox;
MSG msg;
// Check if we are already running to prevent crossing over items in the listbox
if (running) return;
running = true;
// Load DLL
if (!afdInitDLL(&afdDLL, &afdData)) {
    MessageBox("Error Loading afddata.dll", "Error", 0);
	return;
}
// Replace m_lstResult with the name given to a variable assigned to your list box control for the results
listBox = &m_lstResult;
// Clear out any existing items in the list
listBox->ResetContent();
// Reset Cancel flag
cancelFlag = false;
// Update Data so we can read the lookup variable
UpdateData(TRUE);
// Set the lookup
strcpy(details.Lookup, m_txtLookup); // Change this to the postcode or record key you wish to lookup
// Carry out the lookup (Can alter the operation to retrieve N&N list items if desired)
retVal = (afdData)(afdFieldSpec, AFD_LIST_ALIAS_LOCALITY, (char*)&details);
// Abort with Message if error or user cancelled
if (retVal < 0) {
    AFDErrorText(retVal, msgTxt);
    MessageBox(msgTxt, "Error", 0);
    running = false;
    return;
}
// Now add matching records to the list box
while (retVal >= 0) {
    // make up list item
    strncpy(listItem, details.List, sizeof(details.List));
    listItem[sizeof(details.List)] = '\0';
    // Add the item to the list box
    listBox->AddString(listItem);
    // Give user the chance to cancel and allow list box to update
    if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    // Check if user cancelled
    if (cancelFlag) {
        MessageBox("Search Cancelled", "Cancelled", 0);
        return;
    }
    retVal = (afdData)(afdFieldSpec, AFD_GET_NEXT + AFD_LIST_ALIAS_LOCALITY, (char*)&details);
}
// Check results have been returned
if (listBox->GetCount() == 0)
    MessageBox("No Results Found", "Error", 0);
else {
    listBox->SetCurSel(0); // Select First item in the list
    OnSelchangeLstResult(); // Set this to your list change method to simulate selecting the first list item
}
// free DLL instance
FreeLibrary(afdDLL);
afdDLL = (HINSTANCE)NULL;
running = false;

String Utility Functions – Depeciated and Unsupported

These are provided for compatibility with existing applications which may depend on them but for new developments we would recommend you use in-built functions which are included with most modern development environments.

To carry out a string operation you would pass the string to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2.

For example, a valid lookup string for our hosted service to search for instances of “is” and replace them with “it” in the string “this is a test” would be as follows:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=String&Task=SearchReplace&Fields=Standard&Search=is&Replace=it&Lookup=this%20is%20a%20test.

The String Utility Tasks supported and the parameters required are as follows:

Task Parameters Description
SearchReplace Search
Replace
Lookup
All occurrences in the specified Lookup field of the string specified in the Search field are replaced with the string in the Replace field.
SearchReplaceCase Search
Replace
Lookup
This is the same as SearchReplace but is case sensitive.
Capitalise Lookup This corrects the capitalisation of the Lookup field. For example ‘commercial STREET’ would become ‘Commercial Street’.
CleanLine Lookup This cleans the Lookup field by removing spurious characters that should not be in an address line, e.g. a trailing comma.
CheckPostcode Lookup This checks if the string specified in the Lookup field looks like a postcode.
CleanPostcode Lookup This cleans the postcode specified in the Lookup field to tidy up the postcode specified.
AbbreviateCounty Lookup This provides the Royal Mail Approved county abbreviation for the county specified in the Lookup field if one exists.

The resulting string will be found in the Lookup Field of the single Item which will be returned. When using the CleanPostcode function the Outcode and Incode portions of the postcode (portion before and after the space) will also be available in the separate Outcode and Incode Fields which are present in the XML returned.

' Example VB code for a Search/Replace String Operation:
' Declare XML Objects and variables
Dim xmlDoc As Object
Dim root As Object
Dim pcFromNode As Object
Dim dataNode As Object
Dim itemNodes As Object
Dim xmlLocation As String
' Initialise the Microsoft XML Document Object Model
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Build up the XML query string
xmlLocation = AFD_SERVER + "/afddata.pce?"
xmlLocation = xmlLocation + "Serial=" + AFD_SERIAL_NUMBER + "&"
xmlLocation = xmlLocation + "Password=" + AFD_PASSWORD + "&"
xmlLocation = xmlLocation + "UserID=" + AFD_USER_ID + "&"
xmlLocation = xmlLocation + "Data=String&Fields=Standard"
' Set the task (see String operations below for options
xmlLocation = xmlLocation + "&Task=SearchReplace"
' Set the Lookup, Search and Replace parameters
xmlLocation = xmlLocation + "&Lookup=" + txtLookup.Text ' Change txtLookup to your string entry textbox
xmlLocation = xmlLocation + "&Search=" + txtSearch.Text ' Change txtSearch to your search entry textbox
xmlLocation = xmlLocation + "&Replace=" + txtReplace.Text ' Change txtReplace to your replace entry textbox
' Load the XML from the webserver with the query string
xmlDoc.Load (xmlLocation)
' Check for any XML Parser error
If xmlDoc.parseError.errorCode < 0 Then
    Msgbox "Error: " & xmlDoc.parseError.reason & vbCrLf & "Microsoft.XMLDOM Error Code: " & Str(xmlDoc.parseError.errorCode)
	Exit Sub
End If
' Check if PCE returned an error and if the document is valid
Set root = xmlDoc.documentElement
Set dataNode = root.selectSingleNode("Result")
Set itemNodes = root.selectNodes("Item")
If dataNode Is Nothing or itemNodes Is Nothing Then
    Msgbox "Invalid PCE XML Document"
    Exit Sub
End If
If Val(dataNode.Text) < 1 Then
    Set dataNode = root.selectSingleNode("ErrorText")
    If dataNode Is Nothing Then
        Msgbox "Invalid PCE XML Document"
    Else
        Msgbox dataNode.Text ' Show the user the error
    End If
    Exit Sub
End If
' The updated string is held in itemNodes(0).selectSingleNode("Lookup").Text

Grid Utility Functions – UK Address Management Only

These functions are used to carry out operations related to grid references and latitude and longitude values. You can convert between GB and Irish based grid references and also convert to and from latitude and longitude values. The facility to convert a value in kilometers to miles and vice-versa, return an approximate grid reference for a location and also calculate the distance between two geographical locations is also included.

To carry out a grid operation you would pass the grid or latitude and longitude to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2.

For example, a valid URL string for our hosted service to convert the GB grid reference 40660, 28650 to latitude and longitude (Irish based grids would also be returned for it) would be as follows:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Grid&Task=Convert&Fields=Standard&GBGridE=40660&GBGridN=28650

The Grid Utility Tasks supported and the parameters supported are as follows:

Task Parameters Description
Convert1m
Convert
GBGridE, GBGridN
Or NIGridE, NIGridN
Or Latitude, Longitude
Or TextualLatitude,
TextualLongitude
And/Or Miles/Km
Converts a GB or NI based grid reference, or latitude and longitude value to all other grid reference types and latitude and longitude values. The Convert1m function returns grids to a 1m resolution (6 digit), whereas Convert returns 5 digit grids.
LookupLocation1m
LookupLocation
Lookup Looks up a town, locality, or partial postcode specified in the Lookup field and provides an approximate grid reference and latitude and longitude values for the location if a match is found. Multiple matches may be returned if the location is ambiguous. The LookupLocation1m function returns grids to a 1m resolution (6 digit), whereas LookupLocation returns 5 digit grids.
Distance1m
Distance
GBGridE, GBGridN
Or NIGridE, NIGridN
Or Latitude, Longitude

AND:

GBGridEFrom,
GBGridNFrom
Or NIGridEFrom,
NIGridNFrom
Or LatitudeFrom,
LongitudeFrom
Calculates the distance between a pair of grid references or latitude and longitude values specified. You will need to set a grid or latitude and longitude value in both the normal fields and those prefixed with “From” to find the distance in both Miles and Km. The Distance1m function returns grids to a 1m resolution (6 digit), whereas Distance returns 5 digit grids.

You can then read the resulting grid reference, latitude and longitude values, or Km and Miles values as appropriate for the operation you have carried out and the data that you require.

' Example VB code for converting a GB based grid reference:
' Declare XML Objects and variables
Dim xmlDoc As Object
Dim root As Object
Dim pcFromNode As Object
Dim dataNode As Object
Dim itemNodes As Object
Dim xmlLocation As String
' Initialise the Microsoft XML Document Object Model
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Build up the XML query string
xmlLocation = AFD_SERVER + "/afddata.pce?"
xmlLocation = xmlLocation + "Serial=" + AFD_SERIAL_NUMBER + "&"
xmlLocation = xmlLocation + "Password=" + AFD_PASSWORD + "&"
xmlLocation = xmlLocation + "UserID=" + AFD_USER_ID + "&"
xmlLocation = xmlLocation + "Data=Grid&Fields=Standard"
' Set the task (see Grid operations below for options
xmlLocation = xmlLocation + "&Task=Convert1m"
' Set the GBGridE and GBGridN parameters
xmlLocation = xmlLocation + "&GBGridE=406600" ' Change 406600 to the grid easting value you wish to convert
xmlLocation = xmlLocation + "&GBGridN=286500" ' Change 286500 to the grid northing value you wish to conver
' Load the XML from the webserver with the query string
xmlDoc.Load (xmlLocation)
' Check for any XML Parser error
If xmlDoc.parseError.errorCode < 0 Then
    Msgbox "Error: " & xmlDoc.parseError.reason & vbCrLf & "Microsoft.XMLDOM Error Code: " & Str(xmlDoc.parseError.errorCode)
    Exit Sub
End If
' Check if PCE returned an error and if the document is valid
Set root = xmlDoc.documentElement
Set dataNode = root.selectSingleNode("Result")
Set itemNodes = root.selectNodes("Item")
If dataNode Is Nothing or itemNodes Is Nothing Then
    Msgbox "Invalid PCE XML Document"
    Exit Sub
End If
If Val(dataNode.Text) < 1 Then
    Set dataNode = root.selectSingleNode("ErrorText")
    If dataNode Is Nothing Then
        Msgbox "Invalid PCE XML Document"
    Else
        Msgbox dataNode.Text ' Show the user the error
    End If
    Exit Sub
End If
' Other elements of details hold converted values, e.g.
'   Latitude is held in itemNodes(0).selectSingleNode("Latitude").Text
'   Longitude is held in itemNodes(0).selectSingleNode("Longitude").Text
' Grid operations, set Task to one of the following:
' Convert1m - Set the GB Grid Reference, NI Grid Reference, Latitude or Longitude values and the rest of the properites will be filled in giving conversions for any of these items to any other.  Can also convert km to miles and vice-versa.
' LookupLocation1m - Set the lookup property to a location name (e.g. Locality or Town) and a grid reference approximation will be returned if matched.
' Distance1m - Set a grid reference or latitude and longitude values in both the standard fields and the fields prefixed with From and this will calculate the distance between those two points.

Email Utility Function – UK Address Management Only

This function is used to validate the format of an email address is correct and that the domain specified has a valid mail server registered for it.

To carry out an email operation you would pass the email address to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2.

For example, a valid URL string for our hosted service to validate the email addresss support@afd.co.uk would be as follows:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Email&Task=Full&Fields=Standard&Email=support@afd.co.uk

The Email Utility Tasks supported and the required parameter is as follows:

Task Parameter Description
Full Email Full email validation including live domain lookup
Format Email Validate email address format is correct only
TLD Email Validate email format is correct and the top level domain exists
Local Email Validate email format, top level domain and for well known domains carry out
Live Email Validate email format, top level domain and server response (if enabled)

The function will return a result >=0 if the email address is valid.

' Example VB code for converting a GB based grid reference:
' Declare XML Objects and variables
Dim xmlDoc As Object
Dim root As Object
Dim pcFromNode As Object
Dim dataNode As Object
Dim itemNodes As Object
Dim xmlLocation As String
' Initialise the Microsoft XML Document Object Model
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Build up the XML query string
xmlLocation = AFD_SERVER + "/afddata.pce?"
xmlLocation = xmlLocation + "Serial=" + AFD_SERIAL_NUMBER + "&"
xmlLocation = xmlLocation + "Password=" + AFD_PASSWORD + "&"
xmlLocation = xmlLocation + "UserID=" + AFD_USER_ID + "&"
xmlLocation = xmlLocation + "Data=Email&Fields=Standard"
' Set the task (see Email operations below for options
xmlLocation = xmlLocation + "&Task=Full"
' Set the Email parameter
xmlLocation = xmlLocation + "&Email=support@afd.co.uk" ' Change support@afd.co.uk to the email address you wish to validate
' Load the XML from the webserver with the query string
xmlDoc.Load (xmlLocation)
' Check for any XML Parser error
If xmlDoc.parseError.errorCode < 0 Then
    Msgbox "Error: " & xmlDoc.parseError.reason & vbCrLf & "Microsoft.XMLDOM Error Code: " & Str(xmlDoc.parseError.errorCode)
	Exit Sub
End If
' Check if PCE returned an error and if the document is valid
Set root = xmlDoc.documentElement
Set dataNode = root.selectSingleNode("Result")
If dataNode Is Nothing Then
    Msgbox "Invalid PCE XML Document"
    Exit Sub
End If
If Val(dataNode.Text) < 1 Then
    Set dataNode = root.selectSingleNode("ErrorText")
    If dataNode Is Nothing Then
        Msgbox "Invalid PCE XML Document"
    Else
        Msgbox dataNode.Text ' Show the user the error
    End If
    Exit Sub
Else
    Msgbox “Email Address Valid”
End If
' Email operations, set Task to one of the following:
' Full - Full email validation including live domain lookup
' Format - Validate email addres format is correct only
' TLD - Validate email format is correct and the top level domain exists
' Local - Validate email format, top level domain and for well known domains carry out additional local part checks
' Live - Validate email format, top level domain and server response (if enabled)

Clean Function – UK Address Management Only

Requires a Refiner API License

The clean function allows an address, for example from a database, to be cleaned, i.e. where possible matched to Postcode Plus and therefore given a correct deliverable address.

To clean an address you would pass a query string to the afddata.pce URL on the Postcode Everywhere XML server as described in section 5.2. You should add a parameter for address fields specifying the address you wish to clean. These do not need to match up to the actual fields, for example if you have Address Line 1, Address Line 2, Address Line 3 and Postcode in your database you could set these to Property, Street, Locality and Postcode fields parameters and they will be cleaned and returned in the correct named fields when matched. Note that if you set any non-address fields they will be ignored.

For example, a valid lookup string for our hosted service to clean the address “276c, Roton Park Road, Roton Park, Warwikshire, B16 6DE” would be:

http://pce.afd.co.uk/afddata.pce?Serial=000000&Password=PASSWORD&UserID=MyApp&Data=Address&Task=Clean&Fields=Standard&Property=276c&Street=Roton%20Park%20Road&Town=Roton%20Park&PostalCounty=Warwikshire&Postcode=B16%206DE

The Result field returned will be set to a value less than zero in the case where an address cannot be fully matched. This could be because the address was unmatchable, International, or an ambiguous result was found (see Section 4.1.9 for details of these return codes). An address will still be returned as this will include the address with Field Placement correction which you can use if you desire.

Where the Result field contains a positive value (greater than zero) this means that the address has been uniquely matched. You may still like to examine the return value as this will give details as to the level to which the address was matched (see Section 4.1.9 for details of these return codes). Many other fields are also avaliable with additional (non-address data) which you may require.

In the case of an ambiguous or suggested result (return code is -102, -103, or -104) the first address returned from the function will be the original address with field placement. For non-batch processes you may wish to present a list of addresses for the user to choose from, as these will all be contained in the returned XML. However you cannot pass the keys back to the API on record selection through Postcode Everywhere as these are not permanent records and as such will not be available if looked up on a different thread or after another lookup. It is therefore important to read records in and store them from the XML following the lookup if you wish to do this.

' Example VB code for an Address Management Clean:
' Declare XML Objects and variables
Dim xmlDoc As Object
Dim root As Object
Dim dataNode As Object
Dim itemNodes As Object
Dim listNode As Object
Dim keyNode As Object
Dim resultCode As Long
Dim xmlLocation As String
' Initialise the Microsoft XML Document Object Model
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
' Replace lstResult with the name of your list box if you wish to display ambiguous results
With lstResult
    ' Clear out any existing items in the list
    .Clear
    ' Build up the XML query string
    xmlLocation = AFD_SERVER + "/afddata.pce?"
    xmlLocation = xmlLocation + "Serial=" + AFD_SERIAL_NUMBER + "&"
    xmlLocation = xmlLocation + "Password=" + AFD_PASSWORD + "&"
    xmlLocation = xmlLocation + "UserID=" + AFD_USER_ID + "&"
    xmlLocation = xmlLocation + "Data=Address&Task=Clean&Fields=Standard"
    ' Set the parameters to specify the address that you wish to clean
    xmlLocation = xmlLocation + "&Organisation=" + txtSearchOrganisation.Text
    xmlLocation = xmlLocation + "&Property=" + txtSearchProperty.Text
    xmlLocation = xmlLocation + "&Street=" + txtSearchStreet.Text
    xmlLocation = xmlLocation + "&Locality=" + txtSearchLocality.Text
    xmlLocation = xmlLocation + "&Town=" + txtSearchTown.Text
    xmlLocation = xmlLocation + "&Postcode=" + txtSearchPostcode.Text
    ' Load the XML from the webserver with the query string to clean the address
    xmlDoc.Load (xmlLocation)
    ' Check for any XML Parser error
    If xmlDoc.parseError.errorCode < 0 Then
        Msgbox "Error: " & xmlDoc.parseError.reason & vbCrLf & "Microsoft.XMLDOM Error Code: " & Str(xmlDoc.parseError.errorCode)
        Exit Sub
    End If
    ' Check if the document is valid
    Set root = xmlDoc.documentElement
    Set dataNode = root.selectSingleNode("Result")
    Set itemNodes = root.selectNodes("Item")
    If dataNode Is Nothing or itemNodes Is Nothing Then
        Msgbox "Invalid PCE XML Document"
        Exit Sub
    End If
    resultCode = Val(dataNode.Text)
    ' Show the resulting address
    Set dataNode = itemNodes(0).selectSingleNode("Name")
    If Not (dataNode Is Nothing) Then txtName.Text = dataNode.Text
        Set dataNode = itemNodes(0).selectSingleNode("Organisation")
    If Not (dataNode Is Nothing) Then txtOrganisation.Text = dataNode.Text
        Set dataNode = itemNodes(0).selectSingleNode("Property")
    If Not (dataNode Is Nothing) Then txtProperty.Text = dataNode.Text
        Set dataNode = itemNodes(0).selectSingleNode("Street")
    If Not (dataNode Is Nothing) Then txtStreet.Text = dataNode.Text
        Set dataNode = itemNodes(0).selectSingleNode("Locality")
    If Not (dataNode Is Nothing) Then txtLocality.Text = dataNode.Text
        Set dataNode = itemNodes(0).selectSingleNode("Town")
    If Not (dataNode Is Nothing) Then txtTown.Text = dataNode.Text
        Set dataNode = itemNodes(0).selectSingleNode("Postcode")
    If Not (dataNode Is Nothing) Then txtPostcode.Text = dataNode.Text
    ' Show cleaning status
    Set dataNode = root.selectSingleNode("ErrorText")
    If dataNode Is Nothing Then
        Msgbox "Invalid PCE XML Document"
    Else
        Msgbox dataNode.Text
    End If
End With

While the default is fine for most users, If you wish to set any of the advanced cleaning options you can do this by adding those options to the Task string after the word Clean, e.g. Task=Clean0AS.

The options supported are as follows: (Please see the main Refiner manual for more detail regarding each of these options)

  • 0 - Specifies the default cleaning mode where the address is fully cleaned
  • 1 - Specifies that the input record will only be cleaned if the address can be verified against the supplied postcode.
  • 2 – Specifies that only full matches should be returned
  • 3 – Uses Attach Mode only (fields are returned based on the postcode)
  • N – Use non-separated fields (Useful for databases where fields are not seperated, e.g. the street and town are entered on the same line with no comma etc. between them)
  • A – No Ambiguous Matches (do not return list of addresses to choose from if the address cannot be uniquely matched)
  • S – No Suggested Matches (do not return a suggested match along with the original address if the address cannot be matched but there is a possible unique match)
  • U – Assume the Postcode is correct (this option allows less reliable matching on the assumption that the postcode is correct if the address cannot otherwise be verified. In Attach mode this allows a property and postcode to be matched)
  • T – Give Ambiguous Matches in Preference to Street Level (if an address cannot be uniquely matched to an individual property the original property information is normally retained, this option gives the ambiguous addresses to choose from instead).
  • P – Match PO Box Last (Some PO Box addresses contain some Street address information too even though the address is meant for a PO Box. If you wish Refiner to try and match it to a street address first then select this option).
  • L – Retain Alias Localities (If the address is matched using an alias locality this will be retained in the address – Alias Localities are not normally retained as they are not required for the address to be deliverable).
  • O – Do not move data to Organisation (Normally Refiner will put additional address data for street level only matches in the property field unless they look like an Organisation or there is already a property. Specifying this option ensures Refiner never returns such data in the Organisation field - useful if you are not going to use the Organisation field returned).
  • W – Do not use the Default DPS (if an address is not matched to a full Delivery Point Record, a default of 9Z is assigned which can still be used for printing bar codes etc., if you do not wish this to be used then use this option)
  • F – Do not use Field Placement (By default if an address cannot be matched Refiner attempts to format the address correctly on return, if you would rather it was left “as-is” then use this option.

Parameters in Detail

The Data Parameter

This is used to specify the type of Data you require and should be one of the following options:

Data Parameter Usage
Address For all address management products, e.g. Postcode, Postcode Plus, Names & Numbers, TraceMaster, ZipAddress and WorldAddress this is used to lookup and search for addresses.
Bank Used to lookup or search for Bank data using BankFinder and also for account or card validation.
Nearest Used to find the Nearest in your database to a specified postcode or location.
List Used to list the alias localities for any address with Postcode Plus, Names & Numbers and TraceMaster. In Names & Numbers and TraceMaster only, this can also list possible field values for most data fields.
Grid Provides a range of Grid utility functions useful for obtaining, converting, or calculating distances for grid references.
Email Provides a utility to validate the format of Email addresses
String – Deprecated Provides a range of String utility functions sometimes useful for addressing.

The Task Parameter

This is used to specify the specific task that you wish to carry out. The possible values for this depend on the type of data being used (the data parameter) and could be one of the following:

Data Parameter Task Parameter Use
Address FastFind To lookup matching addresses quickly from a postcode or search criteria such as “Commercial Street, Birmingham”.
Lookup To lookup matching addresses quickly from a postcode (or zipcode), e.g. “B11 1AA”. Only a full postcode without any property information included will yield results.
PropertyLookup To lookup matching addresses quickly from a postcode (or zipcode), which may optionally include property information to find a match, e.g. “304, B11 1AA”.
Search To search for matching addresses based on specific search criteria.
Retrieve To re-retrieve a previous result, for example when selected from a list.
Clean To clean an address – requires a Refiner API license.
Bank FastFind Used to lookup bank data from a lookup string, for example a sortcode or bank and branch name, e.g. “560036”.
Search To search for matching bank records based on specific search criteria.
Retrieve To re-retrieve a previous result, for example when selected from a list.
Account Used to validate a sort code and account number is valid (that it is a valid number for the bank branch it is held at, which does not guarantee that it exists).
Card Used to validate a card number is valid (that it is a valid number for the type of card, not that it actually exists).
Nearest FastFind To find the Nearest locations quickly from a postcode, location (e.g. locality or town), grid reference, or latitude and longitude value.
MultipleFastFind As above, but where a find string returns multiple possible locations, e.g. Bradford, the user can select the location they require in an additional step to Nearest.
Lookup Find the nearest from a postcode, e.g. “B11 1AA”. Only full postcodes will yield results.
Search To search for matching records in your database matching the criteria that you search on.
Retrieve To re-retrieve a previous result, for example when selected from a list. Uses the primary key to retrieve the record.
List ListAliasLocality Returns all alias localities for the sector that the specified postcode or key resides in.
The following are applicable when using International data only:
ListCountryISO Will return the ISO codes of all available countries.
ListCountry Will return the names of all available countries.
The following are applicable to Names & Numbers and TraceMaster Products Only:
These all return a list of all entries of the data item specified in the data
Setting the lookup parameter will restrict matches to only those items starting with the specified string.
ListForename Returns Forenames (first names).
ListSurname Returns Surnames
ListOrganisation Returns Organisations
ListProperty Returns Properties
ListStreet Returns Streets
ListLocality Returns Localities
ListTown Returns Postal Towns
ListCounty Returns Counties (This includes Postal, Traditional and Administrative County names)
ListMailsortCode Returns Mailsort codes
ListUrbanRuralCode Returns Urban Rural Codes
ListUrbanRuralName Returns Urban Rural Names
ListWardCode Returns Ward Codes
ListWardName Returns Ward Names
ListConstituency Returns Constituencies
ListEERCode Returns EER Codes (European Electoral Region Codes)
ListEERName Returns EER Names
ListAuthorityCode Returns Local / Unitary Authority Codes
ListAuthority Returns Authority Names
ListLEACode Returns LEA Codes (Local Education Authority)
ListLEAName Returns LEA Names
ListTVRegion Returns TV Regions
ListNHSCode Returns NHS Codes
ListNHSName Returns NHS Names
ListNHSRegionCode Returns NHS Region Codes
ListNHSRegionName Returns NHS Region Names
ListPCTCode Return CCG Codes
ListPCTName Return CCG Names
ListCensationCode Returns Censation Codes
ListAffluence Returns Censation Affluence Codes with descriptions
ListLifestage Returns Censation Lifestage Codes with descriptions
ListAdditionalCensusInfo Returns Censation Additional Information with descriptions.
ListHouseholdComposition Returns Household composition codes with descriptions.
ListBusiness Returns Business descriptions
ListSize Returns Company Size catagories
ListSIC Returns SIC Codes
ListCouncilTaxBand Returns Council Tax Bands
ListConstituencyCode Returns Constituency Codes
ListSubCountryName Returns Sub Country Names
ListDevolvedConstituencyCode Returns Devolved Contituency Codes
ListDevolvedConstituencyName Returns Devolved Cnstituency Name
String - Depreciated SearchReplace Replaces instances of x with y in the supplied string.
SearchReplaceCase A case-sensitive version of SearchReplace
Capitalise Corrects capitalisation of the string as appropriate for address fields, e.g. “COMMerCIAL street” becomes “Commercial Street”
CleanLine Cleans an address line, removing spurious characters
CheckPostcode Checks if a postcode is in a valid format.
CleanPostcode Cleans common errors in a postcode, e.g. “B11 IAA” would be changed to “B11 1AA”.
AbbreviateCounty Returns the Royal Mail approved abbreviation (if one exists) for the supplied County name, e.g. “Oxfordshire” becomes “Oxon”.
Grid Convert1m Used to convert a grid reference to latitude and longitude (or vice-versa), a grid reference on the Irish Grid to the GB grid (or vice-versa). Returns 1m resolution grids.
LookupLocation1m Enables a grid reference to be looked up for a specified locality or town. Returns 1m resolution grids.
Distance1m Calculates the distance between two grid references or latitude and longitude values. Returns 1m resolution grids.
Convert Used to convert a grid reference to latitude and longitude (or vice-versa), a grid reference on the Irish Grid to the GB grid (or vice-versa). Returns 10m resolution grids.
LookupLocation Enables a grid reference to be looked up for a specified locality or town. Returns 10m resolution grids.
Distance Calculates the distance between two grid references or latitude and longitude values. Returns 10m resolution grids.
Email Full Full email validation including live domain lookup
Format Validate email addres format is correct only
TLD Validate email format is correct and the top level domain exists
Local Validate email format, top level domain and for well known domains carry out additional checks of the local portion of the address
Live Validate email format, top level domain and server response for the full email address (if enabled on the server)

The Fields Parameter

This parameter provides the list of fields which are to be searched/returned by the XML operation. In most cases you would set this to the Standard preset which is the standard field list for the data and task including fully formatted address fields were appropriate. However, other formats are also available and the List option can be particularly useful to reduce the amount of XML returned if you are presenting a list of results to the user first. You should note that additional XML fields may be added to any of these presets in future releases but fields would not be removed.

For a full list of the fields included in each field preset, please see Appendix J.

Fields Preset Valid for Data Parameters: Provides
List Address, Bank, Nearest Only the bare essential fields to allow the user to select the desired result from a list box. This includes the list item and key and for Address fields also includes the Postcode and PostcodeFrom parameters to allow changed postcodes to be detected.
Standard (All) Returns all applicable fields for the data type, including a fully formatted address, as would be used on an address label, where applicable.
Raw Address , Bank Returns all applicable fields for the data type, but the address is included in the raw PAF format, for example house number, dependant thoroughfare and thoroughfare are returned as individual fields rather than a single Street field.
BS7666 Address Returns all applicable fields for the data type, but the address is included in a BS7666 compliant format which is useful if you require to store addresses in this form.
USA Address Returns fields in the format used in the USA, most useful when used with ZipAddress for looking up US addresses. However this format will also work with UK addresses just as the UK formats will work with US addresses.
Simple Address Returns only the standard UK name and address, list and key fields when you require address data only and wish to minimise the amount of XML data returned.
International Address Recommended for international addresses, but also useable with UK addresses. This returns formatted address lines which provides the address in a format ready for printing on an envelope or address label, as well as component address fields.
Account Bank Contains applicable fields for Account Number validation.
Card Bank Contains applicable fields for Card Number validation.

Alternatively you can specify your own list of fields to return instead of the preset in the format, field1:maximum length 1@field2:maximum length2…

For example:

&Fields=Lookup:255@Name:120@Organisation:120@Property:120@Street:120@Locality:70@Town:30@Postcode:10@PostcodeFrom:8@Key:40@List:512

When doing this you must ensure you include all fields you would like to be input and output, including those you would supply on the query string (such as the Lookup field).

However using one of the presets shown in the above table is the preferred option when using XML.

The Skip Parameter – UK Address Management Only

For address management products the skip parameter can be used to skip records, for example to return the first record on a postcode only.

The available options are as follows:

Field Value Description
None (or blank) Returns all records matching the lookup or search criteria specified.
Address Only the first record per address (e.g. first listed resident) is returned. Only has any effect in Names & Numbers.
Postcode Only the first record per postcode is returned.
Sector Only the first record in each postcode sector is returned. (A postcode sector is the portion of the postcode before the space plus the first digit after it, e.g. B11 1 is a sector).
Outcode Only the first record per Outcode is returned. The Outcode is the portion of the postcode before the space, e.g. B11.
Town Only the first record per Post Town, e.g. Birmingham is returned.
Area Only the first record per Postcode Area is returned. A Postcode Area is the letters at the start of the postcode, e.g. B11 1AA is in Postcode Area B, IM8 is in Postcode Area IM.

Additional Parameters

The following additional parameters can be supplied in the query string to set Common API options:

Parameter Description
Clearing BankFinder Only: Set to "UK" to return UK member (BACS) banks only, set to "Irish" for IPSO member banks only.
NoSort Names & Numbers Only: Set to 1 if you do not wish records to be returned in number sorted order (will instead be sorted by DPS).
ListSurname Names & Numbers Only: Set to 1 to return the surname first in the list return item.
ApproxGrids Address Management Products Containing Grid References Only: Set to 1 to provide an approximate grid reference for the postal town or locality of a postcode where no postcode level grid reference exists in the data.
Postzon Set to 1 to return Royal Mail Postzon grid references in preference to DataTalk GeoRef grids.

Database Parameters for Nearest

When using Nearest you will also need to specify the following parameter to specify the database to use (this is connected too on the server side):

Parameter Description
DBConnect The name of the database to connect to as defined by a Nearest: section in afddata.ini

As a security precaution only databases specified in afddata.ini can be connected to and the settings which are used are specified in that ini file. You need to ensure the afddata.ini file is in your windows folder (e.g. c:\windows or c:\winnt folder) and has a section called “Nearest: ” where DBname is the name used in the DBConnect parameter for PCE calls.

This section requires the following settings to connect to the database:

Parameter Description
Type The Database Type – ODBC, Access, Paradox or XBase.
Name The name of the DSN to connect too in the case of an ODBC database, or the filename in the case of Access, Paradox, or XBase databases.
UID The username if required for an ODBC Connection (can be omitted if not required).
PWD The password if required for an ODBC Connection (can be omitted if not required).
SQL The SQL String to use to Query your database (e.g. SELECT * FROM TABLE). Not required for Paradox or XBase.
Primary The name of the Primary Key Field in your Nearest database.
GridE The name of the field containing the Grid Easting values in your database. If your database does not contain grid references you will need to add a GridE and GridN field and use the product front-end or AFD Refiner to populate these fields with the grid references which Nearest requires to function.
GridN The name of the field containing the Grid Northing values in your database.
List Specifies the fields (comma separated) to use to construct the List. It is recommended that this contains either the Miles or Km field provided by PostcodeEverywhere to provide the distance followed by some of your database fields to identify the record to the user. The list item is often presented in order of distance to allow the user to select the required record. Even if you are going to construct your own list or not use a list it is recommended to configure this correctly for testing purposes.

An example section for connecting to a DSN called Phones4U containing a table called Nearest would be:

[Nearest: phones4u]
Type=ODBC
Name=Phones4U
UID=username
PWD=password
SQL=SELECT * FROM NEAREST
Primary=Postcode
GridE=GridE
GridN=GridN
List=Miles,Postcode,Title

Other Features

Determining the Product in Use

When integrating with Address Management products the same code will work with any of our Address Management products (AFD Postcode, AFD Postcode Plotter, AFD Postcode Plus, AFD Names & Numbers and AFD Names & Numbers TraceMaster).

It is not normally necessary to determine which product has been used as you can integrate with one, e.g. Names & Numbers and the user can use any of our address management products – they will just have less data returned depending on the product they have. However, if for any reason, such as disabling/enabling features of your product - you can use the Product field if you wish to determine which product the user has and that has been used by the Service.

The Product field will contain one of the following values depending on the product being used:

  • AFD Postcode
  • AFD Postcode Plotter
  • AFD Postcode Plus
  • AFD Names & Numbers
  • AFD Names & Numbers TraceMaster

Note that when carrying out a BankFinder operation AFD BankFinder will always be the product name returned.

Using Welsh Data in Postcode Plus

Welsh data is available for Postcode Plus on request. It works alongside the existing English language PAF data and provides Welsh language equivalents for streets, localities and towns in Wales were such equivalents are available.

To obtain address details using the Welsh variant simply set the DataSet parameter when using XML, to “Welsh” prior to making your call to the API. Any operation including lookup’s, searches and retrieving records can be done using either dataset. Note that the data returned when using either dataset will be the same if no Welsh language alternative is available.

You can also retrieve the same record in both Welsh and English simply by calling the API to retrieve the record once with the DataSet property set to an empty string (or English if you prefer) and once set to “Welsh”. For example, if you carry out a lookup for a postcode, as specified in Section 4.2 of this documentation, and add the items to a list box, when the user selects an item from the list you can retrieve the same address in both Welsh and English language variants by using the List Fetch operation described in Section 4.4 twice for the same record, once with the DataSet parameter set to Welsh and once with it not set.

DX Member Data

DX Members can have access to DX data from within Postcode Plus and the API. This enables you to lookup and search for DX addresses just as you can do with Royal Mail postal addresses. Uniquely, the API also allows you to easily identify DX addresses associated with a PAF address to route your mail through a DX member's box wherever possible resulting in savings over Royal Mail.

Postcode Evolution will automatically return a DXNumber and DXExchange field in the XML if you have the DX data enabled.

Fast-find functionality works with DX data as well as postal data. For example, as well as looking up a postcode you can also carry out a fast-find for a DX number and searching for an organisaiton name with fast-find will search both postal and DX data. This allows you to easily combine your lookup’s. When searching you can either search the standard postal fields or specify the DX Number, organisation, exchange or profession to search theDX data instead. (If you only want to specify one set of search fields in your application then placing DX followed by the DX number in the normal street field will work too – town can then be used to specify the exchange if desired).

When results are returned following any lookup or search if the address is also a DX Member the DXNumber, DXExchange and DXProfession fields will also be returned to indicate this. You can format a DX address as follows for printing:

<Organisation>      e.g.    Pannone LLP
DX <DXNumber>           DX 14314
<DXExchange>            MANCHESTER

See Appendix K for a current list of available DX Professions and Exchanges.

International Data

Customers signed up to use our International data service can lookup and search for international addresses in exactly the same way as you do for UK based addresses. The only difference in normal operation is the need to specify the Country or CountryISO code (as parameters in the GET request) of the country that you wish to use in all lookup, search and record retrieval operations. A full list of these codes is given in Appendix L. of this manual.

Making use of the data returned

If you have opted to use Standard, Raw PAF, or BS7666 fields the data will be returned in the same fields as those for the UK (including county in some cases) which you can use to store the data in your database in the same format as you do for UK addresses.

However, when it comes to generating an address label, you should note that the formatting rules for addresses vary from country to country (for example in many Western European countries the post/zip code comes before the town on the same line). Unless you have your own printing or formatting routines for the country in question, you may therefore actually prefer to use our International address format which provides both the consistuent address fields (broadly the same as Raw PAF fields but also adding the Principality, Region and Cedex which is relevant to some international addresses) as well as address label formatted fields (address1 through to address7). This enables you to both have a structure ideal for data storage and for label formatting.

If you need to store addresses in a more UK based format, but then need to format them for printing you can easily do so by carrying out a search operation specifying the address data with the International field type to obtain the address for printing at the time that you wish to generate an address label.

Obtaining a list of countries

You may well wish (using the list of countries in Appendix L) populate a drop-down list of countries in your application for the user to choose from which includes only those countries that you are interested in using. However if you wish to have a complete list you can do so programmatically by calling the Country List function. Details of doing this is given in section 5.8 (for Postcode Everywhere) of this manual.

Notes regarding International addressing

It is important to note that the standards regarding what is an acceptable address vary widely from country to country as do the levels of data which are available. For example while one country may have full address data from Organisation down, another may only be at street or even locality level. So you must accommodate for different levels of data coming back and therefore differing amounts of manual entry which may be required by users of your software to provide a complete address.