Lab 6: Web APIs

View presentation

Section 1: Get API Key

In order to use an API you might need a key. This is the way that the API identifies who is requesting information and whether you have access to the information. For this lab, we’ll be using the Alpha Vantage API, which has data about different financial securities, including stocks, foreign exchange, and cryptocurrencies.

For Alpha Vantage, you can get a free API key at this link.

Make sure to select student for Which of the following best describes you? and fill out the rest of the boxes. Then submit the form. After you do, the webpage should display some text with your API Key. Copy this value and save it somewhere - you’ll need it later in the lab!

Section 2: Make a Simple Request

Now, let’s practice making some requests and retrieving information from urls. In Python, the requests library has all of the functionality you’ll need. Let’s start by installing the requests library - in your terminal type pip3 install requests.

Now we’re going to try and make a request to a cat facts website and get a cat fact. The cat facts website returns a JSON with a fact in it. To see the format of the json, feel free to copy and paste the url into a web browser. The cat facts url we are using is https://catfact.ninja/fact, and it does not take in any parameters.

Task: Make a get request to the cat facts URL (https://catfact.ninja/fact) and print out the fact!

Hint: We want only the fact to be printed out - don’t just print the JSON! Remember to access and print just the fact, refer to the slides for more information on accessing elements in a JSON.


CHECKPOINT:

Call over a TA to check your request. We want to hear your cat facts!


Section 3: Hit the Alpha Vantage API

Now, we’re going to use what we learned about requesting information from a URL to get information from the Alpha Vantage API. Specifically, we’ll be looking at daily stock prices using the daily time series endpoint.

Note: The AlphaVantage API only allows you 25 free credits per day. So, we will be using mocked data first to make sure our code works and then proceeding to using the API itself. For this exercise, pick one company to investigate from the mock data. You can find the mocked JSON files here. These files mimic the output from their API. Copy one of them into a new file in the folder that has your lab stencil.

To load it in, add the following function to your file.

import json

def read_json(filename: str):
	"""Takes in a filename, loads the json file and returns it as a python object"""
	f = open(filename)
	data = json.load(f)
	return data

This function opens your JSON file, reads it and returns a dictionary so that your python code can interact with it. Now you can index into it!

Task: Get yesterday’s opening price for the selected mock JSON. Print out the value.

Now that you know how to navigate the JSON returned by Alpha Vantage, let’s make an API call for a company that isn’t mocked. You can get a list of the S&P 500 companies and their tickers here, but feel free to use any company. You’ll need one company’s stock ticker.

The documentation for the Alpha Vantage API is here. Make sure to click Daily on the sidebar to get the documentation for the correct endpoint. In order to make a request properly, you’ll need to provide a parameters JSON with the symbol, function, and API key specified. The symbol is the stock ticker you just selected and the API key is your key from section 1 of the lab.

Task: Similarly to the cat facts website, make a request to the Alpha Vantage API and get yesterday’s opening price for the selected company’s stock. Print out the value!

Hint: If you want to see the specific format of the response JSON, you can check out this link.

Section 4: Integrate API and Graph Results

Just getting one datapoint from one city doesn’t seem that helpful! With our new knowledge of APIs, we’re going to get data for 5 different cities and plot it. To start, we’ve written code to plot the data for you - you’ll just be getting and transforming the data.

First, run pip3 install plotly to install the plotly library. The code to plot is:

import plotly.graph_objects as go
import requests
from random import randint

def plot_data(data):
	fig = go.Figure()
	for company in data:
		random_rgb = (randint(0, 255), randint(0, 255), randint(0, 255))
		company_data = data[company]
		fig.add_trace(go.Scatter(
			x = [point[0] for point in company_data],
			y = [point[1] for point in company_data],
			name = company,
			line_color = f"rgb({random_rgb[0]}, {random_rgb[1]}, {random_rgb[2]})",
			opacity = 0.8)
		)

	fig.update_layout(
		title="Timeseries of high price for day",
		xaxis_title="timeseries (daily)",
		yaxis_title="stock price (USD)"
	)
	fig.show()

If you have any questions about what this code is doing, feel free to call over a TA.

Task: Copy and paste the above code into a python file. Copy the read_json function from before. Then, write code below it that calls the API for five different companies and reshapes the data so that it can be plotted. First, use the mocked data to ensure you don’t run out of credits. Then select five tickers that are not mocked. Below is an outline of what we want you to write:


CHECKPOINT:

Call over your Lab TA so that they can check your graph.


Section 5: Exploration of API

For this section, we want you to explore a different API. Here is a link to some public APIs to choose from. You may also explore the NWS API (documentation linked here). The only requirements are that you use a different endpoint. Print out something interesting about your selected endpoint.

Here is the documentation about different endpoints that NWS has!


CHECKPOINT:

Call over a TA so they can check your code. Congrats! You’ve finished this week’s lab!