Documentation

 

SmartyStreets Python SDK

If you want to access our APIs (other than the Download API) from a Python application, the SmartyStreets Python SDK can make it a lot easier. Our Python SDK includes ready-made data structures and takes care of all the gritty, low-level HTTP intricacies for you.

Contents

  1. Requirements
  2. How to Get It
    1. pip
    2. Download the Source Code
  3. How to Use It
    1. Demo
    2. Verifying a Single US Street Address
    3. Verifying Multiple US Street Addresses
    4. Sending a Single Lookup to the US ZIP Code API
    5. Sending Multiple Lookups to the US ZIP Code API
    6. Sending the Beginning of an Address to the US Autocomplete API
    7. Sending Text to the US Extract API
    8. Verifying an International Street Address
  4. API Reference Material

Requirements

  1. Have a Python project that is written for Python 2.7 or Python 3.x.
  2. Realize that you need an address verification component.
  3. Wisely conclude that you don't want to build your own address verification component.
  4. Realize that SmartyStreets has already created an address verification component.
  5. Either have the Requests module installed, or sit comfortably, knowing your friend pip will install this dependency for you.
  6. Congratulations! You are now ready to use the SmartyStreets Python SDK.

How to Get It

pip

The easiest way to get your giddy hands on this goodness is by using pip.
Be sure pip is installed, then just pop open your terminal and run

$ pip install smartystreets_python_sdk

Download the Source Code

You can download the source code from the SmartyStreets Python SDK repository on Github. You can then either embed it in your own Python package, or install it into your site-packages effortlessly:

Use the source, Luke!

$ python setup.py install

How to Use It

Demo

Here are a few pieces of example code to show how to use our Python library/SDK.

Verifying a Single US Street Address

import os
from smartystreets_python_sdk import StaticCredentials, exceptions, ClientBuilder
from smartystreets_python_sdk.us_street import Lookup


def run():
	auth_id = os.environ['SMARTY_AUTH_ID']  # We recommend storing your keys in environment variables
	auth_token = os.environ['SMARTY_AUTH_TOKEN']
	credentials = StaticCredentials(auth_id, auth_token)

	client = ClientBuilder(credentials).build_us_street_api_client()
	# client = ClientBuilder(credentials).with_proxy('localhost:8080', 'user', 'password').build_us_street_api_client()
	# Uncomment the line above to try it with a proxy instead

	lookup = Lookup()
	lookup.street = "1600 Amphitheatre Pkwy"
	lookup.city = "Mountain View"
	lookup.state = "CA"

	try:
		client.send_lookup(lookup)
	except exceptions.SmartyException as err:
		print(err)
		return

	result = lookup.result

	if not result:
		print("No candidates. This means the address is not valid.")
		return

	first_candidate = result[0]

	print("Address is valid. (There is at least one candidate)\n")
	print("ZIP Code: " + first_candidate.components.zipcode)
	print("County: " + first_candidate.metadata.county_name)
	print("Latitude: {}".format(first_candidate.metadata.latitude))
	print("Longitude: {}".format(first_candidate.metadata.longitude))

if __name__ == "__main__":
	run()

Verifying Multiple US Street Addresses

import os

from smartystreets_python_sdk import StaticCredentials, exceptions, Batch, ClientBuilder
from smartystreets_python_sdk.us_street import Lookup


def run():
	auth_id = os.environ['SMARTY_AUTH_ID']  # We recommend storing your keys in environment variables
	auth_token = os.environ['SMARTY_AUTH_TOKEN']
	credentials = StaticCredentials(auth_id, auth_token)

	client = ClientBuilder(credentials).build_us_street_api_client()
	batch = Batch()

	batch.add(Lookup())
	batch[0].street = "1600 amphitheatre parkway"
	batch[0].city = "Mountain view"
	batch[0].state = "california"

	batch.add(Lookup("1 Rosedale, Baltimore, Maryland"))  # Freeform addresses work too.
	batch[1].candidates = 10  # Allows up to ten possible matches to be returned (default is 1).

	batch.add(Lookup("123 Bogus Street, Pretend Lake, Oklahoma"))

	batch.add(Lookup())
	batch[3].street = "1 Infinite Loop"
	batch[3].zipcode = "95014"  # You can just input the street and ZIP if you want.

	assert len(batch) == 4

	try:
		client.send_batch(batch)
	except exceptions.SmartyException as err:
		print(err)
		return

	for i, lookup in enumerate(batch):
		candidates = lookup.result

		if len(candidates) == 0:
			print("Address {} is invalid.\n".format(i))
			continue

		print("Address {} is valid. (There is at least one candidate)".format(i))

		for candidate in candidates:
			components = candidate.components
			metadata = candidate.metadata

			print("\nCandidate {} : ".format(candidate.candidate_index))
			print("Delivery line 1: {}".format(candidate.delivery_line_1))
			print("Last line:       {}".format(candidate.last_line))
			print("ZIP Code:        {}-{}".format(components.zipcode, components.plus4_code))
			print("County:          {}".format(metadata.county_name))
			print("Latitude:        {}".format(metadata.latitude))
			print("Longitude:       {}".format(metadata.longitude))
		print("")


if __name__ == "__main__":
	run()

Sending a Single Lookup to the US ZIP Code API

import os

from smartystreets_python_sdk import StaticCredentials, exceptions, ClientBuilder
from smartystreets_python_sdk.us_zipcode import Lookup


def run():
	auth_id = os.environ['SMARTY_AUTH_ID']  # We recommend storing your keys in environment variables
	auth_token = os.environ['SMARTY_AUTH_TOKEN']
	credentials = StaticCredentials(auth_id, auth_token)

	client = ClientBuilder(credentials).build_us_zipcode_api_client()

	lookup = Lookup()
	lookup.city = "Mountain View"
	lookup.state = "California"

	try:
		client.send_lookup(lookup)
	except exceptions.SmartyException as err:
		print(err)
		return

	result = lookup.result
	zipcodes = result.zipcodes
	cities = result.cities

	for city in cities:
		print("\nCity: " + city.city)
		print("State: " + city.state)
		print("Mailable City: {}".format(city.mailable_city))

	for zipcode in zipcodes:
		print("\nZIP Code: " + zipcode.zipcode)
		print("Latitude: {}".format(zipcode.latitude))
		print("Longitude: {}".format(zipcode.longitude))


if __name__ == "__main__":
	run()

Sending Multiple Lookups to the US ZIP Code API

import os

from smartystreets_python_sdk import StaticCredentials, exceptions, Batch, ClientBuilder
from smartystreets_python_sdk.us_zipcode import Lookup


def run():
	auth_id = os.environ['SMARTY_AUTH_ID']  # We recommend storing your keys in environment variables
	auth_token = os.environ['SMARTY_AUTH_TOKEN']
	credentials = StaticCredentials(auth_id, auth_token)

	client = ClientBuilder(credentials).build_us_zipcode_api_client()
	batch = Batch()

	batch.add(Lookup())
	batch[0].zipcode = "12345"  # A Lookup may have a ZIP Code, city and state, or city, state, and ZIP Code

	batch.add(Lookup())
	batch[1].city = "Phoenix"
	batch[1].state = "Arizona"

	batch.add(Lookup("cupertino", "CA", "95014"))  # You can also set these with arguments

	assert len(batch) == 3

	try:
		client.send_batch(batch)
	except exceptions.SmartyException as err:
		print(err)
		return

	for i, lookup in enumerate(batch):
		result = lookup.result
		print("Lookup {}:\n".format(i))

		if result.status is not None:
			print("Status: " + result.status)
			print("Reason: " + result.reason)
			continue

		cities = result.cities
		print("{} City and State match(es):".format(len(cities)))

		for city in cities:
			print("City: " + city.city)
			print("State: " + city.state)
			print("Mailable City: {}".format(city.mailable_city))
			print("")

		zipcodes = result.zipcodes
		print("{} ZIP Code match(es):".format(len(zipcodes)))

		for zipcode in zipcodes:
			print("ZIP Code: " + zipcode.zipcode)
			print("County: " + zipcode.county_name)
			print("Latitude: {}".format(zipcode.latitude))
			print("Longitude: {}".format(zipcode.longitude))
			print("")

		print("***********************************")

if __name__ == "__main__":
	run()

Sending the Beginning of an Address to the US Autocomplete API

import os

from smartystreets_python_sdk import StaticCredentials, ClientBuilder
from smartystreets_python_sdk.us_autocomplete import Lookup


def run():
	auth_id = os.environ['SMARTY_AUTH_ID']  # We recommend storing your keys in environment variables
	auth_token = os.environ['SMARTY_AUTH_TOKEN']
	credentials = StaticCredentials(auth_id, auth_token)
	client = ClientBuilder(credentials).build_us_autocomplete_api_client()
	lookup = Lookup('4770 Lincoln Ave O')

	client.send(lookup)

	print('*** Result with no filter ***')
	print()
	for suggestion in lookup.result:
		print(suggestion.text)

	lookup.add_state_filter('IL')
	lookup.max_suggestions = 5

	suggestions = client.send(lookup)  # The client will also return the suggestions directly

	print()
	print('*** Result with some filters ***')
	for suggestion in suggestions:
		print(suggestion.text)


if __name__ == "__main__":
	run()

Sending Text to the US Extract API

import os
from smartystreets_python_sdk import StaticCredentials, exceptions, ClientBuilder
from smartystreets_python_sdk.us_extract import Lookup


def run():
	auth_id = os.environ['SMARTY_AUTH_ID']  # We recommend storing your keys in environment variables
	auth_token = os.environ['SMARTY_AUTH_TOKEN']
	credentials = StaticCredentials(auth_id, auth_token)

	client = ClientBuilder(credentials).build_us_extract_api_client()

	text = "Here is some text.\r\nMy address is 3785 Las Vegs Av." \
		   "\r\nLos Vegas, Nevada." \
		   "\r\nMeet me at 1 Rosedale Baltimore Maryland, not at 123 Phony Street, Boise Idaho."

	lookup = Lookup(text)

	result = client.send(lookup)

	metadata = result.metadata
	print('Found {} addresses.'.format(metadata.address_count))
	print('{} of them were valid.'.format(metadata.verified_count))
	print()

	addresses = result.addresses

	print('Addresses: \r\n**********************\r\n')
	for address in addresses:
		print('"{}"\n'.format(address.text))
		print('Verified? {}'.format(address.verified))
		if len(address.candidates) > 0:

			print('\nMatches:')

			for candidate in address.candidates:
				print(candidate.delivery_line_1)
				print(candidate.last_line)
				print()

		else:
			print()

		print('**********************\n')


if __name__ == "__main__":
	run()

Verifying an International Street Address

import os

from smartystreets_python_sdk import StaticCredentials, ClientBuilder
from smartystreets_python_sdk.international_street import Lookup


def run():
	auth_id = os.environ['SMARTY_AUTH_ID']  # We recommend storing your keys in environment variables
	auth_token = os.environ['SMARTY_AUTH_TOKEN']
	credentials = StaticCredentials(auth_id, auth_token)
	client = ClientBuilder(credentials).build_international_street_api_client()

	lookup = Lookup("Rua Padre Antonio D'Angelo 121 Casa Verde, Sao Paulo", 'Brazil')
	lookup.geocode = True  # Must be expressly set to get latitude and longitude.

	candidates = client.send(lookup)  # The candidates are also stored in the lookup's 'result' field.

	first_candidate = candidates[0]
	print("Address is {}".format(first_candidate.analysis.verification_status))
	print("Address precision: {}\n".format(first_candidate.analysis.address_precision))

	print("First Line: {}".format(first_candidate.address1))
	print("Second Line: {}".format(first_candidate.address2))
	print("Third Line: {}".format(first_candidate.address3))
	print("Fourth Line: {}".format(first_candidate.address4))
	print("Latitude: {}".format(first_candidate.metadata.latitude))
	print("Longitude: {}".format(first_candidate.metadata.longitude))


if __name__ == "__main__":
	run()