Student, Developer, Technology Advocate
Welcome to my personal website

Guide: Python, Getting Started With RestAPIs and Matplotlib

on Nov. 6, 2016, 9:02 p.m.

In order to pull data from a RestAPI in Python 3, you are going to need to use a module that is able to make requests to a given url. The appropriately named module that I typically use is called, "requests". This guide will actually pull data from a free guest API. We are going to be pulling from kibot.com. Kibot provides a paid service for users to download stock market prices and other various financial information. They return their data in a CSV (Comma Separated Values) which is very easy to work with. In order to get started, import the appropriate modules. If you do not have matplotlib or requests installed already it is as easy as typing in, "pip3 install matplotlib", in the terminal.

import matplotlib.pyplot as plt
import requests
import datetime as dt

The first thing we need to do in order to access the API is to authenticate ourselves as a user. That is as easy as sending a GET request to the appropriate url. Kibot allows users to authenticate with, "http://api.kibot.com/?action=login&user=guest&password=guest". The following login function is pretty straightforward.

def login():
login_request = requests.get("http://api.kibot.com/?action=login&user=guest&password=guest")
if login_request.status_code != 200:
print("Error logging in")
print("Login successful")

In order to get started, I am going to show you an example of a fairly simple API request to Kibot. You can see in the request_url below that there are a few options for parameters that you can query to the API. The only two parameters we can use as a guest however are symbol and period. Essentially, whatever values you input into the symbol/period parameters return stock data for the symbol. In our example below, we chose to query Apple's(AAPL) data for the last 50 days. You could plug in any values you would like. In the raw_data variable we begin to deal with the return values that we got. The API returns us text in the format "date, open, high, low, close, volume". So really all we have to do is split the returned data by "\n", which represents a newline, to get all of the rows of data. Note: the last row of data is useless to us because it is empty. After we have our rows of data we have to split each row by a comma. This is because each row is in CSV format. We then use a for-loop to begin filling up our empty arrays with data.

def pull_data():
request_url = "http://api.kibot.com/?action=history&symbol=AAPL&interval=daily&period=50"
stock_request = requests.get(request_url)
raw_data = stock_request.text

x_axis = []
date_labels = []
opens = []
highs = []
lows = []
closes = []
volumes = []

for each_line in raw_data.split("\n")[:-1]:
split_line = each_line.split(",")
date_labels.append(str(dt.datetime.strptime(split_line[0], '%m/%d/%Y').date()))

return x_axis, date_labels, opens, highs, lows, closes, volumes

In the function above, we are actually returning x_axis and date_labels. This is because we are going to plot our data with an x-axis containing values like, 0, 1, 2, 3, 4... However, we use our actual date strings as the labels so we are able to understand what is actually going on. For the moment, we are not going to be doing anything with the high, low, close, or volume arrays because that will be in the next few guides. The plotting below is very simple. We plot our x and y values and then rename our x labels with the xticks function. We also need to rotate our x-labels to make them more readable.

x_axis, date_labels, opens, highs, lows, closes, volumes = pull_data()

x = x_axis
y = opens
labels = date_labels

plt.plot(x, y)
plt.xticks(x, labels, rotation='vertical')

After running the code above, you should have something like this displayed! In the next few guides we should get into more advanced API querying and matplotlib functionalities.

The code listed above may or may not be the "best" solution. Please be advised that this is just the way I did it. There are normally thousands of different ways to solve the same programming problem. Find an error? Let me know in the contact form below.

Contact Me

Feel free to email me feedback, suggestions, notes, or to just say hello!