Code Examples

Summary

We know that developing code to interact with an API can be a little daunting. The below examples should make the process easier for you and hopefully easy enough for you to feel comfortable pulling and processing the data that you need.

The below code examples stack with one another, so it is beneficial to follow the examples in order.

Securely Referencing API Key With Environment Variables

There are many ways to more securely store and access secrets than directly in source code. One of those ways that is common practice, is to store secrets in environment variables. There are various ways to use environment variables. One way is to first create a .env file at the root of your Python project and in it, store the following line API_KEY=[your API key]. We like this method because it does not force you to use operating system environment variables when developing locally, but it still allows you to use environment variables without pushing up the .env file when deploying your code to production.

Make sure to ignore the .env file before committing to any repository.

from os import environ as env
from dotenv import find_dotenv, load_dotenv

ENV_FILE = find_dotenv()
if ENV_FILE:
    load_dotenv(ENV_FILE)
API_KEY = env.get('API_KEY')

URL Query Parameters

The first query parameter always begins with ?, and any subsequent query parameters use &.

  • Single query
    • For example, with /screener-all/, your only query parameter will be api_key, and so ? is used.
  • Multiple queries:
    • Any endpoint such as /screener-ticker/ requiring one or more query parameters outside of the api_key, will require the use of &.

The below URL Request Modularity section provides full examples. Keep this in mind when developing your code.

URL Request Modularity

Often times when interacting with an API, you will be making requests to multiple endpoints. In an effort to make the code more efficient, you can modularize the URL.

BASE_URL = 'https://prism-api.algo-nomics.com'
TICKER = 'MSFT'
API_KEY = 'your api key'

screener_tabler_url = f'{BASE_URL}/screener-all/?api_key={API_KEY}'
screener_ticker_url = f'{BASE_URL}/screener-ticker/?ticker={TICKER}&api_key={API_KEY}'
spotter_ticker = f'{BASE_URL}/spotter-all/?ticker={TICKER}&api_key={API_KEY}'
spotter_daterange_url = f'{BASE_URL}/spotter-daterange/?start_date=2020-1-1&end_date=2021-1-1&ticker={TICKER}&api_key={API_KEY}'

Retrieving JSON Data

Data returned from all endpoints is in the JSON structure, which maps great with Python dictionaries.

from os import environ as env
from dotenv import find_dotenv, load_dotenv
from urllib.request import urlopen
import json

ENV_FILE = find_dotenv()
if ENV_FILE:
    load_dotenv(ENV_FILE)
API_KEY = env.get('API_KEY')

BASE_URL = 'https://prism-api.algo-nomics.com'
TICKER = 'MSFT'

url = f'{BASE_URL}/screener-all/?api_key={API_KEY}'

with urlopen(url) as response:
  body = response.read()
data =  json.loads(body)

Processing JSON Data

When using the json library to load the JSON data returned by the API, you will have a Python dictionary ready for processing. How you want to proceed with processing the dictionary depends on the endpoint you queried.

Some endpoints have a single JSON item or multiple JSON items. For example, spotter-latest returns something like ...

{
  "2023-4-10": "Normal"
}

To process these endpoints, you could write ...

for key in data:
  date = key
  classification = data[key]

Other endpoints have several JSON structures with multiple items each. For example, screener-all returns something like ...

{
  {
    "ticker": "AMT",
    "price": 208.35,
    "volume": 1664531,
    "pct_yr_return": -2.94405366376298,
    "market_cap": 97017347434,
    "name": "American Tower Corporation",
    "sector": "Real Estate",
    "spotter": "Normal",
    "risk_class": "High"
  },
  {
    "ticker": "AMZN",
    "price": 102.17,
    "volume": 37150391,
    "pct_yr_return": 19.051503146119806,
    "market_cap": 1046966650808,
    "name": "Amazon.com, Inc.",
    "sector": "Consumer Discretionary",
    "spotter": "Normal",
    "risk_class": "High"
  }
}

To process this endpoint, you could write ...

for entry in data:
  ticker = entry['ticker']
  price = entry['price']
  volume = entry['volume']

For more advanced data processing, you can easily convert the results to a Pandas data frame ...

import pandas as pd

data = pd.DataFrame(data)