Created
December 14, 2018 18:37
-
-
Save kmjones1979/a2b5c52fa4ca5b46fe55f0ea164af249 to your computer and use it in GitHub Desktop.
Zip Code Distance Check via API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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