Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import urllib.request
- import urllib.response
- from urllib.error import HTTPError
- import json
- from os.path import join
- '''
- This is a very shortened Python class for retrieving API data
- from just about anywhere. This bit of code works for 90% of
- anything I do. There caveats though:
- Caveats:
- 1) __init__() builds the API URL for you with "&" as the delimiter
- A clear example of what it does is commented out:
- self.options = "&".join(myList)
- 2) Take a close look at the kinds of variables your API provider
- wants to see
- 3) options_dict is a Python dict (see the example) below for weather
- that makes it easy to see variable names and values you want to pass
- 4) startswith_url will probably need to be specially constructed
- manually after seeing what base URL queries the API provider
- expects. In the larger Python class that I use I have methods
- for constructing all kinds of custom URLs but this is much
- more complex. Best to keep it simple!
- 5) This snippet only pulls JSON data. XML can be retrieved almost the
- same way -- I would recommend xmltodict (what I use). I can provide
- a larger version of this Python class later if you want.
- '''
- class APIRetrieve:
- def __init__(self,startswith_url,options_dict,debug=False):
- #self.options = "&".join(myList)
- self.debug = debug
- self.options = []
- self.data = {}
- options_list = []
- for key in options_dict:
- options_list.append("%s=%s" % (key,options_dict[key]))
- options = "&".join(options_list)
- self.full_url = ("%s&%s" % (startswith_url,options))
- if (debug == True):
- print ("%s" % self.full_url)
- def APIRequestJSON(self):
- req = urllib.request.Request(self.full_url)
- try:
- response = urllib.request.urlopen(req).read().decode("utf-8")
- self.data=json.loads(response)
- except HTTPError as e:
- print(e.read().decode("utf-8"))
- return self.data
- '''
- The following function will pull a simple weather query from Open Weather
- You can create your own API call by checking the needs of your API provider
- and entering into the options = {} dictionary.
- In this case we are passing the APPID with the access key provided to us after
- registering with Open Weather. We are also passing one variable (zip = 98230).
- The variable for your account ID may be named something other than APPID -- check
- the API provider's documentation. Common examples are APIKEY, KEY, ID, etc.
- Once APIRetrieve constructs the & delimited URL it will look like:
- http://api.openweathermap.org/data/2.5/weather?&APPID=df58cfc63456b48a97f21a63f561b572&zip=98230
- You can enter this URL into a web browser just to test it.
- As mentioned (above) in the APIRetrieve class comments base_url will need to be
- manually assembled per your API provider's instructions.
- All options (name=value) can be neatly placed inside the options={} dict. You can put as many
- variables into options as the API allows.
- '''
- def test_json_weather():
- base_url = "http://api.openweathermap.org/data/2.5/weather?"
- options = {
- 'zip' : '98230',
- 'APPID' : 'df58cfc63456b48a97f21a63f561b572'
- }
- api_weather = APIRetrieve(base_url,options,True)
- current_weather = api_weather.APIRequestJSON()
- print(current_weather)
- test_json_weather()
- #
- # END
- #
Advertisement
Add Comment
Please, Sign In to add comment