- C#
- Python
- NodeJS
Address Validation Canada 2 C# Code Snippet
using AVCA2Reference;
namespace address_validation_canada_2_dot_net.SOAP
{
/// <summary>
/// Provides functionality to call the ServiceObjects AVCA2 SOAP service's ValidateCanadianAddressV2 operation,
/// retrieving validated Canadian address information (e.g., corrected address, municipality, province, postal code)
/// for a given input with fallback to a backup endpoint for reliability in live mode.
/// </summary>
public class ValidateCanadianAddressV2Validation
{
private const string LiveBaseUrl = "https://sws.serviceobjects.com/AVCA2/api.svc/soap";
private const string BackupBaseUrl = "https://swsbackup.serviceobjects.com/AVCA2/api.svc/soap";
private const string TrialBaseUrl = "https://trial.serviceobjects.com/AVCA2/api.svc/soap";
private readonly string _primaryUrl;
private readonly string _backupUrl;
private readonly int _timeoutMs;
private readonly bool _isLive;
/// <summary>
/// Initializes URLs, timeout, and IsLive.
/// </summary>
public ValidateCanadianAddressV2Validation(bool isLive)
{
_timeoutMs = 10000;
_isLive = isLive;
_primaryUrl = isLive ? LiveBaseUrl : TrialBaseUrl;
_backupUrl = isLive ? BackupBaseUrl : TrialBaseUrl;
if (string.IsNullOrWhiteSpace(_primaryUrl))
throw new InvalidOperationException("Primary URL not set.");
if (string.IsNullOrWhiteSpace(_backupUrl))
throw new InvalidOperationException("Backup URL not set.");
}
/// <summary>
/// This operation returns validated Canadian address information, including corrected address,
/// municipality, province, postal code, and additional details like time zone and PO Box status.
/// </summary>
/// <param name="Address">Address line of the address to validate (e.g., "50 Coach Hill Dr").</param>
/// <param name="Address2">Secondary address line (e.g., "Apt 4B"). Optional.</param>
/// <param name="Municipality">The municipality of the address (e.g., "Kitchener"). Optional if postal code is provided.</param>
/// <param name="Province">The province of the address (e.g., "Ont"). Optional if postal code is provided.</param>
/// <param name="PostalCode">The postal code of the address (e.g., "N2E 1P4"). Optional if municipality and province are provided.</param>
/// <param name="Language">The language for the response (e.g., "EN", "FR", "EN-Proper"). Optional.</param>
/// <param name="LicenseKey">The license key to authenticate the API request.</param>
public async Task<CanadianAddressResponseV2> ValidateCanadianAddressV2(string Address, string Address2, string Municipality, string Province, string PostalCode, string Language, string LicenseKey)
{
ValidateCanada2Client clientPrimary = null;
ValidateCanada2Client clientBackup = null;
try
{
// Attempt Primary
clientPrimary = new ValidateCanada2Client();
clientPrimary.Endpoint.Address = new System.ServiceModel.EndpointAddress(_primaryUrl);
clientPrimary.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);
CanadianAddressResponseV2 response = await clientPrimary.ValidateCanadianAddressV2Async(
Address, Address2, Municipality, Province, PostalCode, Language, LicenseKey).ConfigureAwait(false);
if (_isLive && !ValidResponse(response))
{
throw new InvalidOperationException("Primary endpoint returned null or a fatal error (TypeCode=3) for ValidateCanadianAddressV2");
}
return response;
}
catch (Exception primaryEx)
{
try
{
clientBackup = new ValidateCanada2Client();
clientBackup.Endpoint.Address = new System.ServiceModel.EndpointAddress(_backupUrl);
clientBackup.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);
return await clientBackup.ValidateCanadianAddressV2Async(
Address, Address2, Municipality, Province, PostalCode, Language, LicenseKey).ConfigureAwait(false);
}
catch (Exception backupEx)
{
throw new InvalidOperationException(
$"Both primary and backup endpoints failed.\n" +
$"Primary error: {primaryEx.Message}\n" +
$"Backup error: {backupEx.Message}");
}
finally
{
clientBackup?.Close();
}
}
finally
{
clientPrimary?.Close();
}
}
private static bool ValidResponse(CanadianAddressResponseV2 response) => response?.Error == null || response.Error.TypeCode != "3";
}
}
Address Validation Canada 2 Python Code Snippet
from suds.client import Client
from suds import WebFault
from suds.sudsobject import Object
class ValidateCanadianAddressV2Soap:
def __init__(self, license_key: str, is_live: bool = True, timeout_ms: int = 15000):
"""
Initialize the ValidateCanadianAddressV2Soap client for the ServiceObjects AVCA2 API.
Parameters:
license_key: Service Objects AVCA2 license key.
is_live: Whether to use live or trial endpoints.
timeout_ms: SOAP call timeout in milliseconds.
"""
self.is_live = is_live
self.timeout = timeout_ms / 1000.0
self.license_key = license_key
# WSDL URLs
self._primary_wsdl = (
"https://sws.serviceobjects.com/AVCA2/api.svc?wsdl"
if is_live
else "https://trial.serviceobjects.com/AVCA2/api.svc?wsdl"
)
self._backup_wsdl = (
"https://swsbackup.serviceobjects.com/AVCA2/api.svc?wsdl"
if is_live
else "https://trial.serviceobjects.com/AVCA2/api.svc?wsdl"
)
def validate_canadian_address_v2(
self,
address: str,
address2: str,
municipality: str,
province: str,
postal_code: str,
language: str
) -> Object:
"""
Calls the ValidateCanadianAddressV2 SOAP API to retrieve validated Canadian address information.
Parameters:
address: Address line of the address to validate (e.g., "50 Coach Hill Dr").
address2: Secondary address line (e.g., "Apt 4B"). Optional.
municipality: The municipality of the address (e.g., "Kitchener"). Optional if postal code is provided.
province: The province of the address (e.g., "Ont"). Optional if postal code is provided.
postal_code: The postal code of the address (e.g., "N2E 1P4"). Optional if municipality and province are provided.
language: The language for the response (e.g., "EN", "FR", "EN-Proper", "FR-Proper"). Optional.
Returns:
suds.sudsobject.Object: SOAP response containing validated address details or error.
Raises:
RuntimeError: If both primary and backup endpoints fail.
"""
# Common kwargs for both calls
call_kwargs = dict(
Address=address,
Address2=address2,
Municipality=municipality,
Province=province,
PostalCode=postal_code,
Language=language,
LicenseKey=self.license_key,
)
# Attempt primary
try:
client = Client(self._primary_wsdl)
# Override endpoint URL if needed:
response = client.service.ValidateCanadianAddressV2(**call_kwargs)
# If response invalid or Error.TypeCode == "3", trigger fallback
if response is None or (
hasattr(response, "Error")
and response.Error
and response.Error.TypeCode == "3"
):
raise ValueError("Primary returned no result or Error.TypeCode=3")
return response
except (WebFault, ValueError, Exception) as primary_ex:
# Attempt backup
try:
client = Client(self._backup_wsdl)
response = client.service.ValidateCanadianAddressV2(**call_kwargs)
if response is None:
raise ValueError("Backup returned no result")
return response
except (WebFault, Exception) as backup_ex:
msg = (
"Both primary and backup endpoints failed.\n"
f"Primary error: {str(primary_ex)}\n"
f"Backup error: {str(backup_ex)}"
)
raise RuntimeError(msg)
Address Validation Canada 2 NodeJS Code Snippet
import { soap } from 'strong-soap';
/**
* @summary
* A class that provides functionality to call the ServiceObjects AVCA2 (Address Validation - Canada) SOAP service's ValidateCanadianAddressV2 endpoint,
* retrieving validated Canadian address information with fallback to a backup endpoint for reliability in live mode.
*/
class ValidateCanadianAddressV2Soap {
/**
* @summary
* Initializes a new instance of the ValidateCanadianAddressV2Soap class with the provided input parameters,
* setting up primary and backup WSDL URLs based on the live/trial mode.
* @param {string} Address - Address line of the address to validate (e.g., "50 Coach Hill Dr").
* @param {string} Address2 - Secondary address line (e.g., "Apt 4B"). Optional.
* @param {string} Municipality - The municipality of the address (e.g., "Kitchener"). Optional if postal code is provided.
* @param {string} Province - The province of the address (e.g., "Ont"). Optional if postal code is provided.
* @param {string} PostalCode - The postal code of the address (e.g., "N2E 1P4"). Optional if municipality and province are provided.
* @param {string} Language - The language for the response (e.g., "EN", "FR", "EN-Proper", "FR-Proper"). Optional.
* @param {string} LicenseKey - Your license key to use the service.
* @param {boolean} isLive - Value to determine whether to use the live or trial servers.
* @param {number} timeoutSeconds - Timeout, in seconds, for the call to the service.
* @throws {Error} Thrown if LicenseKey is empty or null.
*/
constructor(Address, Address2, Municipality, Province, PostalCode, Language, LicenseKey, isLive = true, timeoutSeconds = 15) {
this.args = {
Address,
Address2,
Municipality,
Province,
PostalCode,
Language,
LicenseKey
};
this.isLive = isLive;
this.timeoutSeconds = timeoutSeconds;
this.LiveBaseUrl = 'https://sws.serviceobjects.com/AVCA2/api.svc?wsdl';
this.BackupBaseUrl = 'https://swsbackup.serviceobjects.com/AVCA2/api.svc?wsdl';
this.TrialBaseUrl = 'https://trial.serviceobjects.com/AVCA2/api.svc?wsdl';
this._primaryWsdl = this.isLive ? this.LiveBaseUrl : this.TrialBaseUrl;
this._backupWsdl = this.isLive ? this.BackupBaseUrl : this.TrialBaseUrl;
}
/**
* @summary
* Asynchronously calls the ValidateCanadianAddressV2 SOAP endpoint, attempting the primary endpoint
* first and falling back to the backup if the response is invalid (Error.TypeCode == '3') in live mode
* or if the primary call fails.
* @returns {Promise<Object>} A promise that resolves to an object containing validated address details or an error.
* @throws {Error} Thrown if both primary and backup calls fail, with detailed error messages.
*/
async invokeAsync() {
try {
const primaryResult = await this._callSoap(this._primaryWsdl, this.args);
if (this.isLive && !this._isValid(primaryResult)) {
console.warn("Primary returned Error.TypeCode == '3', falling back to backup...");
const backupResult = await this._callSoap(this._backupWsdl, this.args);
return backupResult;
}
return primaryResult;
} catch (primaryErr) {
try {
const backupResult = await this._callSoap(this._backupWsdl, this.args);
return backupResult;
} catch (backupErr) {
throw new Error(`Both primary and backup calls failed:\nPrimary: ${primaryErr.message}\nBackup: ${backupErr.message}`);
}
}
}
/**
* @summary
* Performs a SOAP service call to the specified WSDL URL with the given arguments,
* creating a client and processing the response into an object.
* @param {string} wsdlUrl - The WSDL URL of the SOAP service endpoint (primary or backup).
* @param {Object} args - The arguments to pass to the ValidateCanadianAddressV2 method.
* @returns {Promise<Object>} A promise that resolves to an object containing the SOAP response data.
* @throws {Error} Thrown if the SOAP client creation fails, the service call fails, or the response cannot be parsed.
*/
_callSoap(wsdlUrl, args) {
return new Promise((resolve, reject) => {
soap.createClient(wsdlUrl, { timeout: this.timeoutSeconds * 1000 }, (err, client) => {
if (err) return reject(err);
client.ValidateCanadianAddressV2(args, (err, result) => {
const response = result?.ValidateCanadianAddressV2Result;
try {
if (!response) {
return reject(new Error("SOAP response is empty or undefined."));
}
resolve(response);
} catch (parseErr) {
reject(new Error(`Failed to parse SOAP response: ${parseErr.message}`));
}
});
});
});
}
/**
* @summary
* Checks if a SOAP response is valid by verifying that it exists and either has no Error object
* or the Error.TypeCode is not equal to '3'.
* @param {Object} response - The response object to validate.
* @returns {boolean} True if the response is valid, false otherwise.
*/
_isValid(response) {
return response && (!response.Error || response.Error.TypeCode !== '3');
}
}
export { ValidateCanadianAddressV2Soap };