Articles

 

Using USPS APIs in Python

Do you want to know how to use the USPS API in Python? We'll show you how, and share step-by-step examples with you. (You may also want to check out our video tutorial on how to use the USPS APIs in Python).

In this article, we'll discuss:

Creating a USPS Account

Before you can use the USPS APIs, you will need to register with the USPS to receive a USERID. This ID is used in the sample code below where "USERID" is mentioned.

Types of USPS APIs

  • There are three USPS APIs available:
    • Address Standardization: validates an address and returns the accepted standardized version of it with other helpful metadata.
    • Zipcode Lookup: a simplified version of the standardization API and returns the zipcode and zip+4 given an address.
    • City/State Lookup: returns the city and state associated with a specified zipcode.
  • You can only make up to 5 requests per API call.
  • XML is used for the Request and Response docs. (Bummer)

Code Example

Note that this sample requires a USERID (see Register above).

Address Standardization Sample Code


# python 3
import urllib.request
import xml.etree.ElementTree as ET

requestXML = """
<?xml version="1.0"?>
<AddressValidateRequest USERID="">
	<Revision>1</Revision>
	<Address ID="0">
		<Address1>2335 S State</Address1>
		<Address2>Suite 300</Address2>
		<City>Provo</City>
		<State>UT</State>
		<Zip5>84604</Zip5>
		<Zip4/>
	</Address>
</AddressValidateRequest>
"""

#prepare xml string doc for query string
docString = requestXML
docString = docString.replace('\n','').replace('\t','')
docString = urllib.parse.quote_plus(docString)

url = "http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=" + docString
print(url + "\n\n")

response = urllib.request.urlopen(url)
if response.getcode() != 200:
	print("Error making HTTP call:")
	print(response.info())
	exit()

contents = response.read()
print(contents)

root = ET.fromstring(contents)
for address in root.findall('Address'):
	print()
	print("Address1: " + address.find("Address1").text)
	print("Address2: " + address.find("Address2").text)
	print("City:     " + address.find("City").text)
	print("State:    " + address.find("State").text)
	print("Zip5:     " + address.find("Zip5").text)
                    

Code Discussion

The first section is the XML request document. In this sample we cheated a bit and just did a multi-line string.
In the XML document string, you will need to specify your USERID that you received when you registered with USPS.


requestXML = """
<?xml version="1.0"?>
<AddressValidateRequest USERID="">
	<Revision>1</Revision>
	<Address ID="0">
		<Address1>2335 S State</Address1>
		<Address2>Suite 300</Address2>
		<City>Provo</City>
		<State>UT</State>
		<Zip5>84604</Zip5>
		<Zip4/>
	</Address>
</AddressValidateRequest>
"""
                    

Next, we prepared the xml document string so it can be used on the URL query string. We did this by removing all tabs and newlines, then url encoding the document.

We then build the complete URL and echo it to the screen for debugging purposes.

Finally, we make the HTTP GET call using urllib.request.urlopen() and check the response code.


#prepare xml string doc for query string
docString = requestXML
docString = docString.replace('\n','').replace('\t','')
docString = urllib.parse.quote_plus(docString)

url = "http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=" + docString
print(url + "\n\n")

response = urllib.request.urlopen(url)
if response.getcode() != 200:
	print("Error making HTTP call:")
	print(response.info())
	exit()
                    

The last section consists of reading the response and printing the raw contents. Then we parse the response into a true XML document and output a few of the returned fields to demonstrate how to access XML elements.


contents = response.read()
print(contents)

root = ET.fromstring(contents)
for address in root.findall('Address'):
	print()
	print("Address1: " + address.find("Address1").text)
	print("Address2: " + address.find("Address2").text)
	print("City:     " + address.find("City").text)
	print("State:    " + address.find("State").text)
	print("Zip5:     " + address.find("Zip5").text)
                    

Alternative Address Validation APIs

SmartyStreets also provides an API set to validate addresses. So why would SmartyStreets assist in using an API that isn't theirs?

The answer is simple - we care. We want you to get your job done, and if you really want to use the USPS API, then hopefully this article will help you.

However, we think that once you see how much easier the SmartyStreets Python SDK is to use, you will want to use it instead of the USPS APIs. And, if you do, you'll get excellent customer service in the process. And of course we won't even mention that SmartyStreet APIs are blazingly fast!

Take a moment and compare the sample code above with the SmartyStreets Python SDK sample code.

When you compare the USPS API experience with the SmartyStreets API experience, you'll see that SmartyStreets wins, every time. From the easy-to-use JSON response, to the stellar support, and the faster response times, and the fact that you can make up to 100 requests per API call to SmartyStreets APIs, SmartyStreets wins everytime.

Try SmartyStreets for yourself with a free demo account. You'll be glad that you did.

This site uses cookies for analytics, personalized content, and ads. By continuing to browse this site, you agree to this use.
Consuming raw or undercooked cookie dough may increase your risk of foodborne illness.