Python sample

The sample obtains an API key, reuses it, obtains a new one when it becomes invalid, retries on temporary failures and reads all pages of a result. It uses the requests package.

import time
import requests

BASE_URL = "https://api-qa.ihsmarkit.com"
USERNAME = "username"
PASSWORD = "password"

session = requests.Session()
apikey = None


def login():
    """Obtain an API key. Reuse it for as long as it is valid."""
    global apikey
    r = session.post(BASE_URL + "/apikey", data={"username": USERNAME, "password": PASSWORD})
    r.raise_for_status()
    apikey = r.text


def get(path, params=None, attempts=5):
    """GET a URL with the API key, re-authenticating and retrying where appropriate."""
    global apikey
    delay = 1
    for _ in range(attempts):
        if apikey is None:
            login()
        r = session.get(BASE_URL + path, params=params,
                        headers={"Authorization": "Bearer " + apikey})
        if r.status_code == 200:
            return r
        error = r.json() if r.headers.get("Content-Type", "").startswith("application/json") else {}
        print(r.status_code, error.get("errorCode"), error.get("errorMessage"), "requestId", error.get("requestId"))
        if error.get("errorCode") == "INVALID_API_KEY":
            apikey = None  # obtain a new key and repeat the request
        elif r.status_code == 429 or r.status_code >= 500:
            time.sleep(delay)  # back off before retrying
            delay = min(delay * 2, 60)
        else:
            r.raise_for_status()  # the request is wrong; do not retry
    raise RuntimeError("Giving up on " + path)


def read_all(path, params):
    """Read all pages of a latest or timeseries request."""
    params = dict(params, envelope="true", limit=1000)
    while True:
        body = get(path, params).json()
        records = body["latest"] if "latest" in body else body["timeseries"]
        yield from records
        if not records or "after" not in body:
            return
        params["after"] = body["after"]


for record in read_all("/namespace/Entity/latest", {"format": "JSON"}):
    print(record)

Reading the stream

The stream is read by requesting the message after the last one, immediately, also after an EMPTY message:

after = "head"
while True:
    message = get("/namespace/stream", {"after": after}).json()
    after = message["after"]
    if message.get("messageType") == "UPDATE":
        process(message["data"])  # in another thread, so that polling continues

Start with after=head to read only new messages, or with a stored after value to continue where you stopped. Store after after you have processed a message.