################################################################################
# Call a Web Service
# Sends SQL command
# Receives results as JSON
# Converts JSON to list of dictionaries 
################################################################################
import urllib.request, urllib.parse
import json

def call(user, pswd, db, sql): 

    sql = urllib.parse.quote(sql)                   #perform url encoding on the sql

    url      = 'https://workshop.sps.nyu.edu/~sultans/util/rest/REST.py'
    param    = F'user={user}&pswd={pswd}&db={db}&dbtype=sqlite&format=json'
    sql      = 'sql=' + sql
    full_url = url +'?'+ param +'&'+ sql

    response = urllib.request.urlopen(full_url)     #call the web service 

    status  = response.status                       #should be 200 
    reason  = response.reason                       #should be OK
    headers = response.info()                       #a dictionary of response headers                

    content = response.read()                       #read the returned data
#   content = content.decode("utf-8")               #convert bytes into string
#   print(content)                                  #debug only
    list = json.loads(content)                      #convert JSON into a list of dictionaries

    return(list)            #return sql results as list of dictionaries

#list = call('demo','demo','demo','select * from student')                  #for debugging
#print(list)                                                                #for debugging