---
title: "9fin 0.1 Authentication: getting a token"
description: "Start here. Get a token and one function, api_get, that every other guide in the series uses."
url: "https://console.9fin.com/guides/authentication"
image: "https://console.9fin.com/_og/d/c_Ocean.takumi,title_~OWZpbiAwLjEgQXV0aGVudGljYXRpb246IGdldHRpbmcgYSB0b2tlbg,description_~U3RhcnQgaGVyZS4gR2V0IGEgdG9rZW4gYW5kIG9uZSBmdW5jdGlvbiwgYXBpX2dldCwgdGhhdCBldmVyeSBvdGhlciBndWlkZSBpbiB0aGUgc2VyaWVzIHVzZXMu,props_eyJ0aGVtZSI6eyJtb2RlIjoibGlnaHQiLCJjb2xvcnMiOnsicHJpbWFyeSI6IiMwOTVDRUYifX19,p_Ii9ndWlkZXMvYXV0aGVudGljYXRpb24i,s_AZ89_wj414r_Z9So.png"
---

# 9fin 0.1 Authentication: getting a token

**APIs used in this notebook**

| API            | Version | Endpoints                                  |
| :------------- | :------ | :----------------------------------------- |
| Authentication | n/a     | POST https://authkit.9fin.com/oauth2/token |
| Entity         | 0.5.7   | GET /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](#what-you-need)

A client id and client secret from the [9fin Dev Portal](https://console.9fin.com/), 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](#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:

```bash
export NINEFIN_CLIENT_ID='client_...'
export NINEFIN_CLIENT_SECRET='...'
```

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

```bash
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.

```python
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
```

```python
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](#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:

```bash
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.

```python
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](#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.

```python
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:

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

Sample output, captured October 2026 (21 lines)

```text
{'items': [{'nf_id': 'nf_ent_0004810d42534205a7c1ac317d22c2c4',
   'roles': ['LEVFIN_COMPANY'],
   'website': 'https://trigranit.com',
   'description': 'Real estate investment, development and construction management platform focused on office and mixed-use projects across Central and Eastern Europe.',
   'street_name': 'Trigranit',
   'full_name': 'TRIGRANIT',
   'short_name': None,
   'country_ref_name': 'Hungary',
   'industry_ref_code': 'J202026810',
   'industry_1': 'Real Estate',
   'industry_2': 'REITs and Other Commercial Property Firms',
   'industry_3': 'Real estate activities with own or leased property',
   'cik': None,
   'active_flag': True,
   'alias': [],
   'coverage_region': ['CEEMEA'],
   'created_at': '2026-06-30T10:21:47.486531',
   'modified_at': '2026-07-27T15:46:03.666110'}],
 'next_cursor': 'eyJrIjogImI2NTJiMzEwNzM3NDNmOWIiLCAidiI6IFsibmZfZW50XzAwMDQ4MTBkNDI1MzQyMDVhN2MxYWMzMTdkMjJjMmM0Il19'}
```

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

## [Rate limits](#rate-limits)

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

| API               | Per minute | Per hour | Max limit |
| :---------------- | :--------- | :------- | :-------- |
| News & Content v2 | 100        | 1,000    | 200       |
| Entity            | 1,000      | 10,000   | 100       |
| Instruments       | 1,000      | 10,000   | 200       |

Every response carries your position in both:

```python
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](#reusing-this-in-the-other-notebooks)

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

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

---

Next guide →

0.2 The data model: identifiers and finding a company

<https://console.9fin.com/guides/data-model>