ICS 32 Fall 2020
Programming with Software Libraries
ASSIGNMENTS
Assignment 0
Assignment 1
Assignment 2
Assignment 3
LECTURE NOTES
Week 1
Week 2
Week 3
Week 4
Week 5
Week 6
FINAL PROJECT
Project Requirements
Powered by Jupyter Book
Contents
Introduction
Summary of Program Requirements
Learning Goals
Program Requirements
Assignment 3: Extending the Platform¶
Introduction¶
In assignment 2, you learned how to write a program that connects to and shares information with a program running on another computer. The computers we write programs for today are almost always connected to other computers in some capacity. Whether it is your computer operating system sending data back to its creator, your web browser automatically downloading updates, or you reaching out to friends and family for a video chat, nearly all the programs we use today rely on networked communication to extend their capabilities.
While your Distributed Social (DS) program has the ability to accept, store, and distribute textual information written by your users, it doesn’t yet take advantage of the vast wealth of information available to networked programs today. So for this assignment we are going to be extending the DS platform by adding some new features for your users as they write journal entries.
You have probably noticed how in programs like Slack, Discord, and Facebook Messenger, keywords can be entered into chat conversations that trigger some sort of automatic inclusion or formatting. In Computer Science, this process is called transclusion, which basically refers to the process of using a linking syntax to connect or include content from one source into the content of another. For this assignment, you will be enhancing your journaling feature by adding support for keyword transclusion.
By now, you should have had a chance to digest some of the core principles of networked communication. You have learned about protocols, sockets, and request/response communication with a server. Your work for assignment 3 will focus on locking in these concepts as well as exploring some new ones.
Summary of Program Requirements¶
• Connect to and retrieve data from at least 2 web API’s using Python’s urllib module.
• Use transclusion to parse and replace keywords in a journal entry with content from web API’s.
• Write classes to manage your APIs.
Learning Goals¶
• How to work with public API’s
• Know when and how to write a class
• Understand and handle failures when communicating over HTTP
Program Requirements¶
Part 1¶
When introducing new features to a program or learning a new tool that is unfamiliar, a good place to start is with a test program. So for Part 1, you will temporarily set aside your DS program and focus on building a small test program that can successfully connect to and retrieve data from a public API. You are welcome to use the sample code below to get started.
import urllib, json
from urllib import request,error
def _download_url(url_to_download: str) -> dict:
response = None
r_obj = None
try:
response = urllib.request.urlopen(url_to_download)
json_results = response.read()
r_obj = json.loads(json_results)
except urllib.error.HTTPError as e:
print(‘Failed to download contents of URL’)
print(‘Status code: {}’.format(e.code))
finally:
if response != None:
response.close()
return r_obj
def main() -> None:
zip = “92697”
ccode = “US”
apikey = “YOUR API KEY”
url = “https://api.openweathermap.org/data/2.5/weather?zip={0},{1}&appid={2}”.format(
zip,
ccode,
apikey
)
weather_obj = _download_url(url)
if weather_obj is not None:
print(weather_obj[‘weather’][0][‘description’])
if __name__ == ‘__main__’:
main()

Connecting to the OpenWeather API¶
To use the sample code, you must first create an account and generate an API key at OpenWeather:
• Create an account at: https://home.openweathermap.org/users/sign_up. If you are prompted to input a reason, just enter UCI and Education/Science.
• Once registered, find your API by clicking the “API Keys” link on your account page. Copy your API key and store it somewhere (as a comment in your code, for example).
• Next visit the current weather page. Read through the instructions and build your API call. A basic call should look like this:
api.openweathermap.org/data/2.5/weather?zip={zip code},{country code}&appid={API key}

• You will likely want to customize this based on your personal preferences, so read through the documentation thoroughly to understand the various options for weather data available through the API.
Once you have your own API key, copy it into the apikey variable in the sample code above and run the program to see the result. Notice that the data response from the API is in JSON format. Most web API’s use the JSON format for storing and sending data and since we are already familiar with JSON from a2, we will continue using it here (though it’s worth noting that the OpenWeather API does support HTML and XML formats too). The loads function in Python’s json module should be all you need to use for converting the JSON responses you received into a Python object. Also notice, that in the sample code, the print out only contains the description attribute for the weather. A more complete output might contain detailed information like temperature, barometric pressure, and humidity. To see all the data available from the API response, you can update the sample code to simply print the weather_obj variable.
Now that you have a functioning API call in place, you should start thinking about how to make this information more accessible for your DS program. A good way to go about doing this is to create a class that abstracts away the processing logic you need to write to gain access to weather data. So for the remainder of this part of the assignment, you will write a weather class called OpenWeather that accepts location information and an API key as parameters and returns an object containing weather data. Your class should be written such that the following validity code runs without error:
from OpenWeather import OpenWeather
zipcode = “92697”
ccode = “US”
apikey = “YOUR API KEY”
open_weather = OpenWeather(zipcode,ccode,apikey)
print(“The temperature for {0} is {1} degrees”.format(zipcode, open_weather.temperature))
print(“The high for today in {0} will be {1} degrees”.format(zipcode, open_weather.high_temperature))
print(“The low for today in {0} will be {1} degrees”.format(zipcode, open_weather.low_temperature))
print(“The coordinates for {0} are {1} longitude and {2} latitude”.format(zipcode, open_weather.longitude, open_weather.latitude))
print(“The current weather for {0} is {1}”.format(zipcode, open_weather.description))
print(“The current humidity for {0} is {1}”.format(zipcode, open_weather.humidity))
print(“The sun will set in {0} at {1}”.format(open_weather.city, open_weather.sunset))

Although the sample code that I have supplied does have some error handling, you will likely want to attend to the various errors that can arise when connecting to remote API’s more gracefully than what I have supplied. Therefore, you will need to understand the different types of errors that occur when communicating over HTTP. Many different conditions can arise that your program may or may not need to communicate to your end user. For example, an invalid API key requires a different set of action than the remote server going down. Therefore, your OpenWeather class should be able to cleanly handle and inform a user about the following conditions:
• Loss of local connection to the Internet
• 404 or 503 HTTP response codes (indicating that the remote API is unavailable)
• Invalid data formatting from the remote API
We will run code that creates these error conditions to evaluate your OpenWeather class as well as your second API (see next section).
Connect to a API of your choice¶
Once you have finished creating your OpenWeather class, you will repeat the process with a new API. You are free to choose any API that you find interesting. Here is a Medium post with some suggestions: A Curated List of 100 Cool and Fun Public APIs to Inspire Your Next Project. There are certainly many more available, so if you don’t find the ones listed in the article interesting, try running a few searches of your own. The main consideration here is to think about how you will present your API data in a DS journal post. The current limitations of the DS server and journaling platform, for example, would prevent you from using a YouTube API to share videos.
Once you settle on an API, you will repeat the steps used in the previous section. Read through the API documentation, if necessary register to get an API key, and build a supporting class to abstract the underlying API complexities from your program (and don’t forget the error handling!).
Finally, since we are not specifying how to write the class for your custom API, you will need to ensure that your class is documented sufficiently enough for us to incorporate it into our testing tools.
Part 2¶
Alright, at this point you should have two classes that retrieve data from web API’s. For the second part of the assignment you will incorporate these classes into the current version of your DS program (where you left of after a2).
You goal for part 2 should be to allow your user to write journal posts with optional keywords that are transcluded into data from your API classes. The actual keywords are up to you, but they must adhere to the following format:
@[KEYWORD]

So for example, the following journal post:
Hello World! Today is the first day of the rest of my life. It is @weatherdescription outside and I am thrilled!
Should transclude to:
Hello World! Today is the first day of the rest of my life. It is sunny outside and I am thrilled!
Okay, that’s a pretty bad example, but you get the idea:)
When your user writes a post, you will also want to inform them about the keywords your program makes available. There are a number of ways to go about accomplishing this task, the most straightforward being a print out of the keywords. However, you might also consider making keyword selection a little more interactive. Either way, you will not be graded on how you inform your user about keyword options, only that you have added this feature.
Extra Credit¶
We will be awarding 1 extra credit point for the successful inclusion of a third API. If you choose to add a third API, you must explicitly define how to use it in your program and let us know via submission page comment that you would like to us to review your third API for extra credit.
How we will grade your submission¶
This assignment will be graded on a 12-point scale, with the 12 points being allocated completely to whether or not you submitted something that meets all of the above requirements. The following rubric will be used:
Requirements and Function | 10 pts
Does the program do what it is supposed to do?
Are there any bugs or errors?
Quality and Design | 2 pts
Is the code well designed?
Is the code clearly documented?
Extra Credit | 1 pt
Does the program makes use of a third API?
By now you should be clearly documenting your code and expending effort to ensure that your code design follows the conventions we have been discussing throughout the class. Therefore, we will be taking a much stricter stance on quality and design than we have in previous assignments.
Assignment 2: Chatting with Friends
Week 1 Notes
By Mark S. Baldwin
© Copyright 2020.