majorcornwallace

API Retrieval for XML and JSON (WIP)

Apr 1st, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. import urllib.request
  2. import urllib.response
  3. from urllib.error import HTTPError
  4. import json
  5. import xmltodict
  6. from os.path import join
  7.  
  8. class APIRetrieve:
  9.     def __init__(self,startswith_url,options_dict):
  10.         #self.options = "&".join(myList)
  11.         self.options = []
  12.         self.data = {}
  13.         options_list = []
  14.         for key in options_dict:
  15.             options_list.append("%s=%s" % (key,options_dict[key]))
  16.         options = "&".join(options_list)
  17.         self.full_url = ("%s&%s" % (startswith_url,options))
  18.         print ("%s" % self.full_url)
  19.        
  20.     def APIRequestJSON(self):
  21.         req = urllib.request.Request(self.full_url)
  22.         try:
  23.             response = urllib.request.urlopen(req).read().decode("utf-8")
  24.             self.data=json.loads(response)
  25.             print(self.data)
  26.         except HTTPError as e:
  27.             print(e.read().decode("utf-8"))
  28.            
  29.         return self.data
  30.            
  31.     def APIRequestXML(self):
  32.         req = urllib.request.Request(self.full_url)
  33.         try:
  34.             response = urllib.request.urlopen(req).read().decode("utf-8")
  35.             self.data=xmltodict.parse(response, process_namespaces=True)
  36.             print(self.data)
  37.         except HTTPError as e:
  38.             print(e.read().decode("utf-8"))
  39.            
  40.         return self.data
Advertisement
Add Comment
Please, Sign In to add comment