Skip to content

Instantly share code, notes, and snippets.

@mbeale
Last active December 31, 2015 13:09
Show Gist options
  • Save mbeale/7991238 to your computer and use it in GitHub Desktop.
Save mbeale/7991238 to your computer and use it in GitHub Desktop.
EasyPost - Python export shipments to csv
#
# This will fetch shipments and ouput them into csv
#
# Dependencies
# python requests lib - pip install requests
# python iso8601 lib - pip install iso8601
#
# Setup
# add your API key to the code
#
# Example
# python shipmentscsv.py -f output2.csv -s 2013-11-01 -e 2013-11-30
#
import requests
import iso8601
import datetime
import csv
from optparse import OptionParser
#options
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write output to file", metavar="FILE")
parser.add_option("-s", "--start", dest="start_date",
help="Start date for export", metavar="YYYY-MM-DD")
parser.add_option("-e", "--end", dest="end_date",
help="End date for export", metavar="YYYY-MM-DD")
(options, args) = parser.parse_args()
if not options.start_date:
print "Start date not specified (-s YYYY-MM-DD)"
exit(1)
if not options.end_date:
print "End date not specified (-e YYYY-MM-DD)"
exit(1)
if not options.filename:
print "File name not specified (-f FILE)"
exit(1)
#config
api_key = 'your api key'
csvfields = ['id',
'tracking_code',
'to_address.street1',
'to_address.city',
'to_address.state',
'to_address.zip',
'postage_label.label_url',
'created_at']
#init values
page = 1
bcontinue = True
utcnow = datetime.datetime.utcnow()
now = datetime.datetime.now()
diff = utcnow - now
end_date = iso8601.parse_date(options.end_date) + diff
start_date = iso8601.parse_date(options.start_date) + diff
#open file for writing
c = csv.writer(open(options.filename, "wb"), quotechar='"', quoting=csv.QUOTE_ALL)
#write headers
c.writerow(csvfields)
#process data
while bcontinue:
r = requests.get('https://api.easypost.com/v2/shipments?page=' + str(page), auth=(api_key,''))
shipments = r.json()
if len(shipments) <= 0:
bcontinue = False
for shipment in shipments:
created_at = iso8601.parse_date(shipment['created_at'])
#if <= enddate and >= startdate, add row
if created_at <= end_date and created_at >= start_date:
row = []
for field in csvfields:
value = shipment
for segment in field.split('.'):
value = value[segment]
row.append(u' '.join(('', value)).encode('utf-8').strip())
c.writerow(row)
#if < startdate, discontinue processing
elif created_at < start_date:
bcontinue = False
page = page + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment