In [1]:
    
import http.client, urllib.request, urllib.parse, urllib.error, base64
import urllib
import json
import pickle
    
In [2]:
    
def metro_line_import(line):
    """Import station data from WMATA API and format it as a dictionary with staion name as the key and the
    [latitude, longitude] as the values"""
    headers = {
    # Request headers
    'api_key': '7f97903f83b24fcaa6dcc929bdb73437',
    }
    params = urllib.parse.urlencode({
        # Request parameters
        'LineCode': line,
    })
    try:
        conn = http.client.HTTPSConnection('api.wmata.com')
        conn.request("GET", "/Rail.svc/json/jStations?%s" % params, "{body}", headers)
        response = conn.getresponse()
        data = response.read()
        #print(data)
        conn.close()
        data_js = json.loads(data)
        line_dic = dict()
        for ii in range(len(data_js['Stations'])):
            line_dic[data_js['Stations'][ii]['Name']] = [data_js['Stations'][ii]['Lat'], data_js['Stations'][ii]['Lon']]
        #print(line_dic)
    except Exception as e:
        print("[Errno {0}] {1}".format(e.errno, e.strerror))
    return line_dic
    
Import the data for each line
In [3]:
    
lines = ['RD', 'YL', 'GR','BL', 'OR', 'SV']
line_stations = []
for ii in range(len(lines)):
    line_stations.append(metro_line_import(lines[ii]))
    
Turn list of dict's into dic with line (key) and stations (value)
In [4]:
    
station_data = dict()
for ii in range(len(lines)):
    station_data[lines[ii]] = line_stations[ii]
    
Use Pickel to save the dictionary of lines with the station locations
In [5]:
    
pickle.dump( station_data, open( "station_data.p", "wb" ) )
    
In [6]:
    
station_data['RD']['Silver Spring']
    
    Out[6]:
In [ ]: