Python library and command line tools to query the UPS API
To install the UPS-API command-line tools and package,
$ pip install ups-api
If installing from source, run the following in the root folder of the repository,
$ pip install -e .
To validate just a single address,
$ ups xav "1600 Pennsylvania Avenue NW, Washington, DC, 20500"
1600 PENNSYLVANIA AVE NW,WASHINGTON,DC,20500
Sometimes there will be more than one candidate,
$ ups xav "1600 Pennsylvania Avenue NW, Washington, DC, 20501"
1600 PENNSYLVANIA AVE NW,WASHINGTON,DC,20500
1600 PENNSYLVANIA AVE NW,WASHINGTON,DC,20502
The ups command can also be run in batch mode where it reads addresses from a CSV file (the csv file is of the form street, city, state, zip),
$ ups xav-batch addresses.csv -o validated_addresses.csv
To validate an address in Python use the UpsXav class,
>>> from ups import Address, UpsXav
>>> address = Address.from_str(
... "1600 Pennsylvania Avenue NW, Washington, DC, 20501"
... )
>>> xav = UpsXav()
>>> addresses = xav.post(address)
>>> for address in addresses:
... print(address)
This will print the following:
1600 PENNSYLVANIA AVE NW,WASHINGTON,DC,20500 1600 PENNSYLVANIA AVE NW,WASHINGTON,DC,20502
A typical request to the UPS Street-level address validator will look something like the following:
>>> data = {
"UPSSecurity": {
"UsernameToken": {"Username": YOUR_USERNAME, "Password": YOUR_PASSWORD},
"ServiceAccessToken": {"AccessLicenseNumber": YOUR_LICENSE},
},
"XAVRequest": {
"Request": {
"RequestOption": "1",
"TransactionReference": {"CustomerContext": ""},
},
"MaximumListSize": "10",
"AddressKeyFormat": {
"ConsigneeName": "",
"BuildingName": "",
"AddressLine": "1600 Pennsylvania Avenue NW",
"PoliticalDivision2": "Washington",
"PoliticalDivision1": "DC",
"PostcodePrimaryLow": "20500",
"CountryCode": "US",
},
},
}
And then to validate,
>>> url = "https://onlinetools.ups.com/rest/XAV"
>>> response = requests.post(url, json=data)
This will generate the following response,
{
"XAVResponse": {
"Response": {
"ResponseStatus": {"Code": "1", "Description": "Success"},
"TransactionReference": {"CustomerContext": ""},
},
"ValidAddressIndicator": "",
"Candidate": {
"AddressKeyFormat": {
"AddressLine": "1600 PENNSYLVANIA AVE NW",
"PoliticalDivision2": "WASHINGTON",
"PoliticalDivision1": "DC",
"PostcodePrimaryLow": "20500",
"PostcodeExtendedLow": "0005",
"Region": "WASHINGTON DC 20500-0005",
"CountryCode": "US",
}
},
}
}
All the stuff you need is in the Candidate section. If there are multiple candidates, the value of Candidate will be a list of AddressKeyFormat objects rather than a single object. If there are no candidates, the section will be empty.