majorcornwallace

API Retrieval for JSON (SIMPLE)

May 11th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.25 KB | None | 0 0
  1. import urllib.request
  2. import urllib.response
  3. from urllib.error import HTTPError
  4. import json
  5. from os.path import join
  6.  
  7. '''
  8. This is a very shortened Python class for retrieving API data
  9. from just about anywhere. This bit of code works for 90% of
  10. anything I do. There caveats though:
  11.  
  12. Caveats:
  13.     1) __init__() builds the API URL for you with "&" as the delimiter
  14.         A clear example of what it does is commented out:
  15.             self.options = "&".join(myList)
  16.     2) Take a close look at the kinds of variables your API provider
  17.         wants to see
  18.     3) options_dict is a Python dict (see the example) below for weather
  19.         that makes it easy to see variable names and values you want to pass
  20.     4) startswith_url will probably need to be specially constructed
  21.         manually after seeing what base URL queries the API provider
  22.         expects. In the larger Python class that I use I have methods
  23.         for constructing all kinds of custom URLs but this is much
  24.         more complex. Best to keep it simple!
  25.     5) This snippet only pulls JSON data. XML can be retrieved almost the
  26.         same way -- I would recommend xmltodict (what I use). I can provide
  27.         a larger version of this Python class later if you want.
  28.  
  29.        
  30. '''
  31. class APIRetrieve:
  32.     def __init__(self,startswith_url,options_dict,debug=False):
  33.         #self.options = "&".join(myList)
  34.         self.debug = debug
  35.         self.options = []
  36.         self.data = {}
  37.         options_list = []
  38.         for key in options_dict:
  39.             options_list.append("%s=%s" % (key,options_dict[key]))
  40.             options = "&".join(options_list)
  41.         self.full_url = ("%s&%s" % (startswith_url,options))
  42.         if (debug == True):
  43.             print ("%s" % self.full_url)
  44.    
  45.     def APIRequestJSON(self):
  46.         req = urllib.request.Request(self.full_url)
  47.         try:
  48.             response = urllib.request.urlopen(req).read().decode("utf-8")
  49.             self.data=json.loads(response)
  50.         except HTTPError as e:
  51.             print(e.read().decode("utf-8"))
  52.    
  53.         return self.data
  54.  
  55. '''
  56. The following function will pull a simple weather query from Open Weather
  57. You can create your own API call by checking the needs of your API provider
  58. and entering into the options = {} dictionary.
  59.  
  60. In this case we are passing the APPID with the access key provided to us after
  61. registering with Open Weather. We are also passing one variable (zip = 98230).
  62. The variable for your account ID may be named something other than APPID -- check
  63. the API provider's documentation. Common examples are APIKEY, KEY, ID, etc.
  64.  
  65. Once APIRetrieve constructs the & delimited URL it will look like:
  66.     http://api.openweathermap.org/data/2.5/weather?&APPID=df58cfc63456b48a97f21a63f561b572&zip=98230
  67.  
  68. You can enter this URL into a web browser just to test it.
  69.  
  70. As mentioned (above) in the APIRetrieve class comments base_url will need to be
  71. manually assembled per your API provider's instructions.
  72.  
  73. All options (name=value) can be neatly placed inside the options={} dict. You can put as many
  74. variables into options as the API allows.
  75.  
  76.  
  77. '''
  78. def test_json_weather():
  79.      base_url = "http://api.openweathermap.org/data/2.5/weather?"
  80.      options = {
  81.         'zip' : '98230',
  82.         'APPID' : 'df58cfc63456b48a97f21a63f561b572'
  83.         }
  84.      api_weather = APIRetrieve(base_url,options,True)
  85.      current_weather = api_weather.APIRequestJSON()
  86.      print(current_weather)
  87.  
  88.      
  89. test_json_weather()
  90.  
  91. #
  92. # END
  93. #
Advertisement
Add Comment
Please, Sign In to add comment