9fin 0.1 Authentication: getting a token

APIs used in this notebook

APIVersionEndpoints
Authenticationn/aPOST https://authkit.9fin.com/oauth2/token
Entity0.5.7GET /v0/entity
Before you start

None. This notebook is the starting point of the series.

Sample output

Every output on this page is a static sample. The results below were captured from a live run in October 2026 and are reproduced here so the page reads without credentials. Figures, article titles, identifiers and API versions were current that day and will have moved on since. Run the notebook yourself for live data.

Start here. All of our APIs take the same bearer token, so this is the one step shared by every workflow in the series. It leaves you with one function, api_get, that the other notebooks call.

What you need

A client id and client secret from the 9fin Dev Portal, and the APIs you want on your key. Keys carry different products, and a 403 Forbidden on a call means that one is not on yours.

Python 3.9 or later, Jupyter, and two packages: requests and pandas.

Where your credentials are read from

Three places, in order, stopping at the first that answers. Nothing is ever written into the notebook.

Environment variables, which is what to use on a server:

export NINEFIN_CLIENT_ID='client_...'
export NINEFIN_CLIENT_SECRET='...'

The macOS Keychain, if you would rather set it once and forget it:

security add-generic-password -s 9fin-api -a client_id     -U -w
security add-generic-password -s 9fin-api -a client_secret -U -w

Both commands prompt for the value rather than taking it on the command line. On Windows and Linux this step is skipped, so use environment variables there.

A hidden prompt, if neither is set.

import os, time, subprocess, requests

def from_keychain(account):
    """Read a secret from the macOS Keychain. Returns None anywhere else."""
    try:
        found = subprocess.run(["security", "find-generic-password", "-s", "9fin-api",
                                "-a", account, "-w"], capture_output=True, text=True, timeout=10)
        return found.stdout.strip() or None
    except (OSError, subprocess.SubprocessError):
        return None
from getpass import getpass

CLIENT_ID     = os.environ.get("NINEFIN_CLIENT_ID")     or from_keychain("client_id")     or getpass("client id: ")
CLIENT_SECRET = os.environ.get("NINEFIN_CLIENT_SECRET") or from_keychain("client_secret") or getpass("client secret: ")

Swapping the credentials for a token

We use OAuth2 client credentials. You post the id and secret once, get an access token back, and send that token as a bearer token on every call. In curl:

curl -sS -X POST https://authkit.9fin.com/oauth2/token \
  -u "$CLIENT_ID:$CLIENT_SECRET" -d grant_type=client_credentials

The token lasts one hour. There is no refresh token, so repeat the exchange to get a new one. Do not send scope=openid: the client credentials grant rejects it.

token() below holds the token and re-authenticates a minute before it expires.

BASE      = "https://api.9fin.com"
TOKEN_URL = "https://authkit.9fin.com/oauth2/token"

_token = {"value": None, "expires": 0.0}

def token():
    """A live access token, reused until it is a minute from expiring."""
    if time.time() >= _token["expires"]:
        reply = requests.post(TOKEN_URL, auth=(CLIENT_ID, CLIENT_SECRET),
                              data={"grant_type": "client_credentials"}, timeout=30)
        reply.raise_for_status()
        _token.update(value=reply.json()["access_token"],
                      expires=time.time() + reply.json()["expires_in"] - 60)
    return _token["value"]

The one function you need

api_get takes a path and any filters you want, attaches the token, and hands back the parsed JSON. Every example in every notebook is a call to this.

It waits and retries on a rate limit, so a long backfill runs unattended.

def api_get(path, **filters):
    """GET any 9fin endpoint and return the parsed JSON."""
    for attempt in range(8):
        reply = requests.get(BASE + path, headers={"Authorization": f"Bearer {token()}"},
                             params=filters, timeout=60)
        if reply.status_code == 429:
            time.sleep(3 * (attempt + 1))
            continue
        reply.raise_for_status()
        return reply.json()
    raise RuntimeError(f"still rate limited after 8 attempts: {path}")

One company record from the Entity API:

api_get("/v0/entity", limit=1)

That is the shape every collection endpoint returns: an items list, and a next_cursor to ask for the page after it.

Rate limits

Two budgets run at once, a per minute and a per hour, and they differ by API:

APIPer minutePer hourMax limit
News & Content v21001,000200
Entity1,00010,000100
Instruments1,00010,000200

Every response carries your position in both:

reply.headers["X-RateLimit-Remaining-minute"], reply.headers["X-RateLimit-Remaining-hour"]

News is both the tightest budget and the one you will lean on hardest, so page size matters more there than anywhere else: at limit=200 a backfill covers the same ground in a tenth of the calls of one asking for 20. api_get waits out a 429 either way, so a long loop finishes regardless, just more slowly.

Reusing this in the other notebooks

api_get, and a token that renews itself. Every other notebook opens with one line:

%run "9fin 0.1 Authentication - getting a token.ipynb"