Skip to content

Instantly share code, notes, and snippets.

@kmjones1979
Created December 14, 2018 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmjones1979/a2b5c52fa4ca5b46fe55f0ea164af249 to your computer and use it in GitHub Desktop.
Save kmjones1979/a2b5c52fa4ca5b46fe55f0ea164af249 to your computer and use it in GitHub Desktop.
Zip Code Distance Check via API
import requests
import csv
# zip code api variables
API_URL = 'https://api.zip-codes.com/ZipCodesAPI.svc/1.0/CalculateDistance/ByZip?'
ZIPS = ["T5T 4J2", "J3V 5K1", "H9R 1C4", "G1V 2L1", "H7T 1C8", "H3B 5K4", "H3P 3E9", "J4Y 0L1", "H1M 1W9", "J1L 1K1", "G2K 1N4"]
# API Key
APIKEY = 'HIDDEN'
# csv variables
FILE = '/root/customers_master.csv'
with open(FILE, 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
#print(row)
for ZIP in ZIPS:
with open('/root/Projects/zipcode-api/output.csv', 'a') as SAVE:
if row['zip'] == "":
print("No Zip","Error")
else:
ORIG = row['zip']
payload = { 'fromzipcode': ORIG, 'tozipcode': ZIP, 'key': APIKEY }
r = requests.get(API_URL, params=payload)
data = r.json()
try:
d = data['DistanceInMiles']
obj = (ORIG + ',' + ZIP + ',' + str(d) + ',')
print(obj)
SAVE.write(obj + '\n' )
except KeyError:
d = "Error"
obj = (ORIG + ',' + ZIP + ',' + str(d) + ',')
print(obj)
SAVE.write(obj + '\n' )
SAVE.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment