0
# Address Validation
1
2
Validate and standardize postal addresses using Google's address validation service with support for USPS CASS certification and comprehensive address component analysis.
3
4
## Capabilities
5
6
### Address Validation
7
8
Validate, standardize, and analyze postal addresses with detailed component breakdown and delivery information.
9
10
```python { .api }
11
def addressvalidation(client, addressLines, regionCode=None, locality=None,
12
enableUspsCass=None):
13
"""
14
Validate and standardize postal addresses.
15
16
Args:
17
client (Client): Google Maps API client instance
18
addressLines (list): List of address line strings representing the
19
unstructured address (e.g., ["1600 Amphitheatre Pkwy", "Mountain View CA"])
20
regionCode (str): Region code in CLDR format (e.g., "US", "GB").
21
Helps improve validation accuracy.
22
locality (str): Locality/city name to assist in validation when
23
not clear from address lines
24
enableUspsCass (bool): Enable USPS CASS validation for US addresses.
25
Provides additional certification and standardization.
26
27
Returns:
28
dict: Address validation response containing:
29
- result: Validation result with standardized address
30
- responseId: Unique identifier for this validation request
31
Contains verdict, address components, geocoding, and delivery info
32
33
Raises:
34
googlemaps.exceptions.ApiError: When API returns an error
35
googlemaps.exceptions.TransportError: When HTTP request fails
36
googlemaps.exceptions.Timeout: When request times out
37
"""
38
```
39
40
## Usage Examples
41
42
### Basic Address Validation
43
44
```python
45
import googlemaps
46
47
gmaps = googlemaps.Client(key='YOUR_API_KEY')
48
49
# Validate a US address
50
address_lines = [
51
"1600 Amphitheatre Pkwy",
52
"Mountain View CA 94043"
53
]
54
55
validation_result = gmaps.addressvalidation(
56
addressLines=address_lines,
57
regionCode="US"
58
)
59
60
# Extract validation results
61
result = validation_result['result']
62
verdict = result['verdict']
63
64
print("Address Validation Results:")
65
print("=" * 30)
66
67
# Overall validation verdict
68
print(f"Input Granularity: {verdict['inputGranularity']}")
69
print(f"Validation Granularity: {verdict['validationGranularity']}")
70
print(f"Geocode Granularity: {verdict['geocodeGranularity']}")
71
72
# Address completeness
73
address_complete = verdict.get('addressComplete', False)
74
print(f"Address Complete: {address_complete}")
75
76
# Check if components were inferred or confirmed
77
if 'hasUnconfirmedComponents' in verdict:
78
print(f"Has Unconfirmed Components: {verdict['hasUnconfirmedComponents']}")
79
80
if 'hasInferredComponents' in verdict:
81
print(f"Has Inferred Components: {verdict['hasInferredComponents']}")
82
```
83
84
### Detailed Address Component Analysis
85
86
```python
87
import googlemaps
88
89
gmaps = googlemaps.Client(key='YOUR_API_KEY')
90
91
# Validate address and analyze components
92
address_lines = ["123 Main St", "Anytown NY 12345"]
93
94
validation_result = gmaps.addressvalidation(
95
addressLines=address_lines,
96
regionCode="US",
97
enableUspsCass=True # Enable USPS certification
98
)
99
100
result = validation_result['result']
101
102
# Analyze address components
103
if 'address' in result:
104
address_info = result['address']
105
106
print("Standardized Address Components:")
107
print("=" * 40)
108
109
# Formatted address
110
if 'formattedAddress' in address_info:
111
print(f"Formatted Address: {address_info['formattedAddress']}")
112
113
# Individual components
114
if 'addressComponents' in address_info:
115
for component in address_info['addressComponents']:
116
component_name = component['componentName']['text']
117
component_type = component['componentType']
118
confirmation_level = component.get('confirmationLevel', 'UNKNOWN')
119
120
print(f"{component_type}: {component_name} ({confirmation_level})")
121
122
# Postal address details
123
if 'postalAddress' in address_info:
124
postal = address_info['postalAddress']
125
print(f"\nPostal Details:")
126
print(f" Region Code: {postal.get('regionCode', 'N/A')}")
127
print(f" Language Code: {postal.get('languageCode', 'N/A')}")
128
print(f" Postal Code: {postal.get('postalCode', 'N/A')}")
129
130
if 'addressLines' in postal:
131
print(f" Standardized Lines:")
132
for i, line in enumerate(postal['addressLines']):
133
print(f" {i+1}: {line}")
134
```
135
136
### USPS CASS Validation
137
138
```python
139
import googlemaps
140
141
gmaps = googlemaps.Client(key='YOUR_API_KEY')
142
143
# US address with USPS CASS validation enabled
144
us_address = [
145
"1 E Main St",
146
"Mesa AZ 85201"
147
]
148
149
usps_validation = gmaps.addressvalidation(
150
addressLines=us_address,
151
regionCode="US",
152
enableUspsCass=True
153
)
154
155
result = usps_validation['result']
156
157
print("USPS CASS Validation Results:")
158
print("=" * 35)
159
160
# Check for USPS data
161
if 'uspsData' in result:
162
usps_info = result['uspsData']
163
164
print(f"USPS Standardized Address:")
165
print(f" First Address Line: {usps_info.get('standardizedAddress', {}).get('firstAddressLine', 'N/A')}")
166
print(f" City: {usps_info.get('standardizedAddress', {}).get('cityName', 'N/A')}")
167
print(f" State: {usps_info.get('standardizedAddress', {}).get('state', 'N/A')}")
168
print(f" ZIP Code: {usps_info.get('standardizedAddress', {}).get('zipCode', 'N/A')}")
169
170
# Delivery point information
171
if 'deliveryPointCode' in usps_info:
172
print(f" Delivery Point: {usps_info['deliveryPointCode']}")
173
174
if 'deliveryPointCheckDigit' in usps_info:
175
print(f" Check Digit: {usps_info['deliveryPointCheckDigit']}")
176
177
# Address record type
178
if 'recordType' in usps_info:
179
print(f" Record Type: {usps_info['recordType']}")
180
181
# ZIP+4 information
182
if 'zipPlusFourCode' in usps_info:
183
print(f" ZIP+4: {usps_info['zipPlusFourCode']}")
184
185
# Check delivery information
186
if 'verdict' in result and 'hasReplacedComponents' in result['verdict']:
187
print(f"Components Replaced: {result['verdict']['hasReplacedComponents']}")
188
```
189
190
### International Address Validation
191
192
```python
193
import googlemaps
194
195
gmaps = googlemaps.Client(key='YOUR_API_KEY')
196
197
# Validate international addresses
198
addresses = [
199
{
200
'lines': ["10 Downing Street", "London SW1A 2AA"],
201
'region': "GB",
202
'name': "UK Address"
203
},
204
{
205
'lines': ["1-1 Marunouchi", "Chiyoda City, Tokyo 100-0005"],
206
'region': "JP",
207
'name': "Japan Address"
208
},
209
{
210
'lines': ["Champs-Élysées", "Paris 75008"],
211
'region': "FR",
212
'name': "France Address"
213
}
214
]
215
216
for addr_info in addresses:
217
print(f"\nValidating {addr_info['name']}:")
218
print("-" * 30)
219
220
validation = gmaps.addressvalidation(
221
addressLines=addr_info['lines'],
222
regionCode=addr_info['region']
223
)
224
225
result = validation['result']
226
227
# Display formatted address
228
if 'address' in result and 'formattedAddress' in result['address']:
229
formatted = result['address']['formattedAddress']
230
print(f"Formatted: {formatted}")
231
232
# Display validation quality
233
if 'verdict' in result:
234
verdict = result['verdict']
235
granularity = verdict.get('validationGranularity', 'UNKNOWN')
236
print(f"Validation Quality: {granularity}")
237
```
238
239
### Batch Address Validation
240
241
```python
242
import googlemaps
243
244
gmaps = googlemaps.Client(key='YOUR_API_KEY')
245
246
def validate_address_list(addresses):
247
"""Validate multiple addresses and return results."""
248
results = []
249
250
for i, addr in enumerate(addresses):
251
try:
252
validation = gmaps.addressvalidation(
253
addressLines=addr.get('lines', []),
254
regionCode=addr.get('region'),
255
locality=addr.get('locality'),
256
enableUspsCass=addr.get('enable_usps', False)
257
)
258
259
result = validation['result']
260
261
# Extract key information
262
address_info = {
263
'original': addr,
264
'formatted': None,
265
'valid': False,
266
'complete': False,
267
'geocoded': False,
268
'components': []
269
}
270
271
# Get formatted address
272
if 'address' in result and 'formattedAddress' in result['address']:
273
address_info['formatted'] = result['address']['formattedAddress']
274
275
# Check validation status
276
if 'verdict' in result:
277
verdict = result['verdict']
278
address_info['complete'] = verdict.get('addressComplete', False)
279
address_info['valid'] = verdict.get('validationGranularity') not in ['GRANULARITY_UNSPECIFIED', 'OTHER']
280
address_info['geocoded'] = verdict.get('geocodeGranularity') not in ['GRANULARITY_UNSPECIFIED', 'OTHER']
281
282
results.append(address_info)
283
284
except Exception as e:
285
results.append({
286
'original': addr,
287
'error': str(e),
288
'valid': False
289
})
290
291
return results
292
293
# Example batch validation
294
address_batch = [
295
{'lines': ["1600 Pennsylvania Ave", "Washington DC"], 'region': 'US', 'enable_usps': True},
296
{'lines': ["350 5th Ave", "New York NY"], 'region': 'US', 'enable_usps': True},
297
{'lines': ["Invalid Address XYZ", "Nowhere"], 'region': 'US'},
298
{'lines': ["221B Baker Street", "London"], 'region': 'GB'}
299
]
300
301
validation_results = validate_address_list(address_batch)
302
303
print("Batch Validation Results:")
304
print("=" * 40)
305
306
for i, result in enumerate(validation_results):
307
print(f"\nAddress {i+1}:")
308
print(f"Original: {result['original']['lines']}")
309
310
if 'error' in result:
311
print(f"Error: {result['error']}")
312
else:
313
print(f"Formatted: {result.get('formatted', 'N/A')}")
314
print(f"Valid: {result['valid']}")
315
print(f"Complete: {result['complete']}")
316
print(f"Geocoded: {result['geocoded']}")
317
```
318
319
### Address Correction and Standardization
320
321
```python
322
import googlemaps
323
324
gmaps = googlemaps.Client(key='YOUR_API_KEY')
325
326
def standardize_address(address_lines, region_code="US"):
327
"""Standardize an address and show corrections."""
328
329
validation = gmaps.addressvalidation(
330
addressLines=address_lines,
331
regionCode=region_code,
332
enableUspsCass=True
333
)
334
335
result = validation['result']
336
337
print(f"Original Address: {' '.join(address_lines)}")
338
339
# Show standardized version
340
if 'address' in result:
341
address_info = result['address']
342
343
if 'formattedAddress' in address_info:
344
formatted = address_info['formattedAddress']
345
print(f"Standardized: {formatted}")
346
347
# Show component-level corrections
348
if 'addressComponents' in address_info:
349
print("\nComponent Analysis:")
350
for component in address_info['addressComponents']:
351
name = component['componentName']['text']
352
comp_type = component['componentType']
353
confirmation = component.get('confirmationLevel', 'UNKNOWN')
354
355
status = ""
356
if confirmation == 'CONFIRMED':
357
status = "✓"
358
elif confirmation == 'UNCONFIRMED_BUT_PLAUSIBLE':
359
status = "?"
360
elif confirmation == 'UNCONFIRMED_AND_SUSPICIOUS':
361
status = "⚠"
362
363
print(f" {comp_type}: {name} [{confirmation}] {status}")
364
365
# Show verdict details
366
if 'verdict' in result:
367
verdict = result['verdict']
368
print(f"\nValidation Summary:")
369
print(f" Address Complete: {verdict.get('addressComplete', False)}")
370
print(f" Has Replacements: {verdict.get('hasReplacedComponents', False)}")
371
print(f" Has Inferences: {verdict.get('hasInferredComponents', False)}")
372
print(f" Validation Level: {verdict.get('validationGranularity', 'UNKNOWN')}")
373
374
# Examples of address standardization
375
test_addresses = [
376
["1600 pennsylvania avenue", "washington dc 20500"], # Case and formatting
377
["350 fifth ave", "new york ny 10118"], # Abbreviated street
378
["1 hacker way", "menlo park ca"], # Modern address
379
["123 main street apt 4b", "anytown ny 12345"] # Apartment number
380
]
381
382
for addr in test_addresses:
383
print("=" * 60)
384
standardize_address(addr)
385
print()
386
```
387
388
### Geocoding Integration with Address Validation
389
390
```python
391
import googlemaps
392
393
gmaps = googlemaps.Client(key='YOUR_API_KEY')
394
395
def validate_and_geocode(address_lines, region_code="US"):
396
"""Validate address and extract geocoding information."""
397
398
validation = gmaps.addressvalidation(
399
addressLines=address_lines,
400
regionCode=region_code
401
)
402
403
result = validation['result']
404
405
address_data = {
406
'original': ' '.join(address_lines),
407
'formatted': None,
408
'coordinates': None,
409
'geocode_quality': None,
410
'valid': False
411
}
412
413
# Extract formatted address
414
if 'address' in result and 'formattedAddress' in result['address']:
415
address_data['formatted'] = result['address']['formattedAddress']
416
417
# Extract geocoding information
418
if 'geocode' in result:
419
geocode_info = result['geocode']
420
421
if 'location' in geocode_info:
422
location = geocode_info['location']
423
address_data['coordinates'] = (
424
location.get('latitude'),
425
location.get('longitude')
426
)
427
428
# Geocoding accuracy
429
if 'bounds' in geocode_info:
430
bounds = geocode_info['bounds']
431
print(f"Geocoding bounds available: {bounds}")
432
433
# Validation quality
434
if 'verdict' in result:
435
verdict = result['verdict']
436
address_data['geocode_quality'] = verdict.get('geocodeGranularity')
437
address_data['valid'] = verdict.get('addressComplete', False)
438
439
return address_data
440
441
# Example usage
442
test_address = ["1600 Amphitheatre Parkway", "Mountain View CA 94043"]
443
result = validate_and_geocode(test_address)
444
445
print("Address Validation + Geocoding:")
446
print(f"Original: {result['original']}")
447
print(f"Formatted: {result['formatted']}")
448
print(f"Coordinates: {result['coordinates']}")
449
print(f"Geocode Quality: {result['geocode_quality']}")
450
print(f"Valid: {result['valid']}")
451
452
# Compare with regular geocoding
453
if result['formatted']:
454
geocode_result = gmaps.geocode(result['formatted'])
455
if geocode_result:
456
geo_location = geocode_result[0]['geometry']['location']
457
print(f"Regular Geocoding: ({geo_location['lat']}, {geo_location['lng']})")
458
```