# Keep your API key out of the browser: a local proxy for financial data, and how to verify live data

Keep the API key out of browser JavaScript with a small local Python proxy that blocks other sites and hides upstream errors, plus four checks after switching to live data.

When a browser-based dashboard calls an API, the thing to avoid above all is leaking the API key. Any key in JavaScript can be read by anyone who opens the page. This page shows how to keep the key out of the browser: a small Python server on your own machine holds it and calls ZENITH Code on the page's behalf.

- Take the key from an environment variable or a hidden prompt. Never put it in code, URLs, or command-line arguments.
- The browser only talks to the local proxy; the proxy adds the key and calls the API.
- After switching to live data, check four things before trusting it: a known value, units, missing values, and sources.

The example fetches Toyota Motor (7203) annual figures from the [income statement endpoint](https://zenithcode.net/en/docs/income-statement). The stock quote endpoint ([`/stable/quote`](https://zenithcode.net/en/docs/quote)) comes last, and only for display **in your own private environment**.

We at [Crabgrass Inc.](https://crabgrass.co.jp/) build [ZENITH Code](https://zenithcode.net/en), an API for financial and disclosure data on Japanese companies. This article is an implementation guide for using our own data.

## Why the key can't live in the browser

Everything that runs in the browser is delivered to the user. A key written in JavaScript can be read in any of these ways:

- The Network tab in developer tools shows the request headers.
- The page source and loaded JavaScript files are open to inspection.
- `localStorage` and cookies can be read directly.

Watch your build tooling too. Environment variables prefixed with `NEXT_PUBLIC_` in Next.js or `VITE_` in Vite are inlined into browser bundles at build time. "It's in an environment variable" doesn't make it secret.

A leaked key lets someone else spend your quota. ZENITH Code accepts keys in the `x-api-key` header and does not accept `?apikey=` in the URL, because URLs tend to end up in access logs and `Referer` headers.

## How to pass the key

Use one of these two:

| Method | Example | Good for |
|---|---|---|
| Environment variable | `ZENITH_API_KEY` | Automation, or injecting from a password manager |
| Hidden prompt | Python's `getpass` | Trying things locally |

Don't pass it as a command-line argument (`--key xxxx`); it stays in shell history and process listings. If you use a `.env` file, add it to `.gitignore` so it never reaches Git.

```python
import getpass
import json
import os
import re
import secrets
import sys
import threading
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

BASE_URL = "https://api.zenithcode.net/stable"
PORT = 8780
ANNUAL_LIMIT = 5
SYMBOL_RE = re.compile(r"^[0-9A-Z]{4,5}$")


def load_api_key() -> str:
    """Read the key from the environment or a hidden prompt, never from argv."""
    key = os.environ.get("ZENITH_API_KEY", "").strip()
    if not key and sys.stdin.isatty():
        key = getpass.getpass("ZENITH API key (hidden): ").strip()
    if not key:
        sys.exit("Set ZENITH_API_KEY or start from a terminal.")
    return key


def call_zenith(api_key: str, path: str, params: dict):
    """Call ZENITH Code. The key is attached to the header here and nowhere else."""
    url = f"{BASE_URL}{path}?{urllib.parse.urlencode(params)}"
    request = urllib.request.Request(url, headers={"x-api-key": api_key, "Accept": "application/json"})
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)
```

The dashboard shows a new key only once, when you create it. Save it somewhere safe right then. If you think it leaked, revoke it in the dashboard and create a new one.

## Build the local proxy

Put a small server that runs only on your machine between the browser and ZENITH Code.

| Leg | Destination | API key |
|---|---|---|
| Browser → proxy | `http://127.0.0.1:8780/api/annual` | Not included |
| Proxy → ZENITH Code | `https://api.zenithcode.net/stable/income-statement` | Added by Python |

Don't let the proxy become an open relay. Accept one specific request, and have the server decide every parameter except the ticker. The response check, `validate_annual`, is in the next section.

```python
UPSTREAM_ERRORS = {401: "key_rejected", 403: "key_forbidden", 429: "rate_or_quota"}


def make_handler(api_key: str, local_token: str):
    gate = threading.Lock()
    origin = f"http://127.0.0.1:{PORT}"

    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *_):
            pass  # don't print URLs or headers to the terminal

        def reply(self, status: int, body: dict):
            data = json.dumps(body, ensure_ascii=False).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Cache-Control", "no-store")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def do_GET(self):
            if self.headers.get("Host") != f"127.0.0.1:{PORT}":
                return self.reply(403, {"error": "local_only"})
            if self.path == "/config.json":
                return self.reply(200, {"token": local_token})
            if self.path == "/":
                page = open(os.path.join(os.path.dirname(__file__), "index.html"), "rb").read()
                self.send_response(200)
                self.send_header("Content-Type", "text/html; charset=utf-8")
                self.send_header("Content-Security-Policy", "default-src 'self'; connect-src 'self'; frame-ancestors 'none'")
                self.send_header("Referrer-Policy", "no-referrer")
                self.end_headers()
                return self.wfile.write(page)
            return self.reply(404, {"error": "not_found"})

        def do_POST(self):
            if (self.headers.get("Host") != f"127.0.0.1:{PORT}"
                    or self.headers.get("Origin") != origin
                    or not secrets.compare_digest(self.headers.get("X-Local-Token", ""), local_token)):
                return self.reply(403, {"error": "local_only"})
            if self.path != "/api/annual":
                return self.reply(404, {"error": "not_found"})
            try:
                length = min(int(self.headers.get("Content-Length", "0")), 1024)
                symbol = str(json.loads(self.rfile.read(length) or b"{}").get("symbol", "")).strip().upper()
            except (ValueError, AttributeError):
                return self.reply(400, {"error": "bad_request"})
            if not SYMBOL_RE.fullmatch(symbol):
                return self.reply(400, {"error": "bad_symbol"})
            if not gate.acquire(blocking=False):
                return self.reply(429, {"error": "busy"})
            try:
                rows = call_zenith(api_key, "/income-statement",
                                   {"symbol": symbol, "period": "annual", "limit": ANNUAL_LIMIT})
                rows = validate_annual(rows, symbol, ANNUAL_LIMIT)
                self.reply(200, {"symbol": symbol, "rows": rows})
            except urllib.error.HTTPError as e:
                # Never relay the upstream body. Map the status to a fixed code.
                self.reply(502, {"error": UPSTREAM_ERRORS.get(e.code, "upstream_failed"), "status": e.code})
            except (urllib.error.URLError, TimeoutError):
                self.reply(502, {"error": "network"})
            except ValueError:
                self.reply(502, {"error": "invalid_response"})
            finally:
                gate.release()

    return Handler


if __name__ == "__main__":
    key = load_api_key()
    token = secrets.token_urlsafe(32)  # regenerated on every start; not the API key
    server = ThreadingHTTPServer(("127.0.0.1", PORT), make_handler(key, token))
    print(f"Open http://127.0.0.1:{PORT}", flush=True)
    server.serve_forever()
```

### Keep other pages from using it

The proxy sits there holding your key. If another site open in your browser could call it in the background, that would be as bad as handing over the key. So every data request is checked three ways:

| Check | What it stops |
|---|---|
| `Host` is `127.0.0.1:8780` | Requests reaching the server under another hostname (DNS rebinding) |
| `Origin` is your own page | Other open sites calling the proxy behind your back |
| `X-Local-Token` matches the startup token | Callers that never loaded your page |

The token is regenerated with `secrets.token_urlsafe(32)` on every start. Your page fetches it from `/config.json` first. Pages on other sites can't read that response because of the browser's same-origin policy. The token isn't the API key, so it's fine for the page to know it.

The proxy also:

- Listens on `127.0.0.1` only, so other devices on your Wi-Fi can't connect. Don't change it to `0.0.0.0`.
- Runs one request at a time, so repeated clicks don't drain your quota.
- Validates the ticker format and fixes `period` and `limit` on the server, so the page can't pass arbitrary parameters.
- Prints no access log, and sends `Cache-Control: no-store` so the browser doesn't keep responses.
- Sends a `Content-Security-Policy` that blocks scripts from anywhere else.

### Don't relay error bodies

If an API call fails, the proxy doesn't pass the upstream body to the page. It returns a fixed code based on the status, on the assumption that error bodies could contain internal details.

| Proxy `error` | Status | Typical cause |
|---|---|---|
| `key_rejected` | 401 | Missing or wrong key |
| `key_forbidden` | 403 | Revoked key, too many keys for the plan, and similar |
| `rate_or_quota` | 429 | Rate limit or quota reached |
| `network` | — | Connection failure or timeout |
| `invalid_response` | — | The response failed the shape check |

Don't retry automatically after an error. If the key or quota is the problem, retries return the same result and only burn quota.

## Validate the response before the page sees it

Check the shape of the data before showing it. A plausible chart built from another company's rows, or from non-annual rows, is harder to notice than an error.

```python
def validate_annual(rows, symbol: str, limit: int) -> list:
    """Check the response shape before display. Raise ValueError on mismatch."""
    if not isinstance(rows, list) or len(rows) > limit:
        raise ValueError("row_count")
    seen = set()
    for row in rows:
        if not isinstance(row, dict) or row.get("symbol") != symbol:
            raise ValueError("symbol_mismatch")
        if row.get("period") != "FY":
            raise ValueError("not_annual")
        period = row.get("fiscalPeriod")
        if not isinstance(period, str) or not re.fullmatch(r"\d{4}-\d{2}", period) or period in seen:
            raise ValueError("fiscal_period")
        seen.add(period)
        for field in ("revenue", "operatingIncome", "netIncome", "operatingMargin"):
            value = row.get(field)
            if value is not None and (isinstance(value, bool) or not isinstance(value, (int, float))):
                raise ValueError("field_type")
    return rows
```

- Stop if there are more rows than `limit`. That catches a wrong parameter returning far more periods than expected.
- An empty array isn't an error. Companies with no reported fiscal years (just after listing, for example) return `[]`. Show "no financial data" instead.
- `null` amounts are allowed. Pass missing values through as missing; never turn them into 0.

Put the code in one file (for example `local_proxy.py`) in this order: `load_api_key` and `call_zenith`, then `validate_annual`, then `make_handler` and the startup block. Place your page's `index.html` in the same folder and run `python3 local_proxy.py`.

## Browser-side code

The page's JavaScript only calls the proxy. Neither the ZENITH Code URL nor the key appears anywhere.

```javascript
const MESSAGES = {
  bad_symbol: "Check the ticker (4 to 5 letters or digits).",
  busy: "Another request is in progress.",
  key_rejected: "Check your API key.",
  key_forbidden: "Check your key's status (revoked, or over the key limit).",
  rate_or_quota: "Request limit reached. Try again later.",
  network: "Check your connection.",
  invalid_response: "Unexpected data format. Display stopped.",
  local_only: "Reload the page.",
};

const { token } = await (await fetch("/config.json")).json();

export async function loadAnnual(symbol) {
  const res = await fetch("/api/annual", {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-Local-Token": token },
    body: JSON.stringify({ symbol }),
  });
  const body = await res.json();
  if (!res.ok) return { error: MESSAGES[body.error] ?? "Couldn't fetch the data." };
  if (body.rows.length === 0) return { error: "No annual financial data for this ticker." };
  return { rows: body.rows };
}
```

Restarting the proxy changes the token, so an old tab gets `local_only`. Reload the page.

## Four checks after switching to live data

A dashboard built on sample data has the same shape as live data but not the same behavior. Once numbers appear, check these four things before you rely on them.

### 1. Does a known value match?

Pick one period with a published value and compare. For Toyota's fiscal year ended March 2025, the production API returned these values on October 27, 2026 at 16:50 JST:

| Field | Value |
|---|---|
| `revenue` | `48036704000000` (¥48.04 trillion) |
| `operatingIncome` | `4795586000000` (¥4.80 trillion) |
| `operatingMargin` | 0.0998 in the API, 9.98% on screen |
| `accountingStandard` | `ifrs` |
| `provenance.docId` | `S100VWVY` |

```python
def smoke_check(rows: list) -> list:
    """Compare one known period. Return a list of differences."""
    expected = {"revenue": 48036704000000, "operatingIncome": 4795586000000}
    row = next((r for r in rows if r["fiscalPeriod"] == "2025-03"), None)
    if row is None:
        return ["no 2025-03 row (is limit too small?)"]
    problems = [f"{k}: {row.get(k)} != {v}" for k, v in expected.items() if row.get(k) != v]
    doc = (row.get("provenance") or {}).get("docId")
    if problems and doc != "S100VWVY":
        problems.append(f"filing ID changed to {doc} (possible correction or replacement)")
    return problems
```

A mismatch isn't automatically a bug. Values can be updated, for example by a correction. Check whether the filing ID changed first.

### 2. Are the units right?

API amounts are in yen; ratios are decimals from 0 to 1. If the screen shows "48,036,704," you're displaying millions; if it shows "0.10%," you forgot to multiply the ratio by 100. Sample data built in millions or percentages will disagree here.

### 3. Did missing values become 0?

Live data contains `null`: ordinary income for IFRS companies, or items with no line on the statement. If you see 0 or 0%, something converted `null` to 0.

### 4. Are sources and timestamps shown?

Confirm each period shows its filing ID and disclosure time. Timestamps come back in UTC; convert to Japan time before display. See [Track the source of every financial figure](https://zenithcode.net/en/docs/cookbook/applied/practice-statements-and-sources).

### How many calls

`limit` is the number of periods in one response, not the number of calls. Five years is still one call. Our docs list both the income statement and quote endpoints at one token per call, available on the Free plan. Check the [pricing page](https://zenithcode.net/en/pricing) for current quota terms.

## Show stock prices only in your private environment

Adding the quote endpoint (`/stable/quote`) to the proxy lets you show the latest close (`price`) and its date (`priceDate`). **Only do this in your own private environment.**

- Stock prices, price changes, and market capitalization are exchange data. They can't be shown or redistributed to third parties on any plan. Even inside a company, only the registered member can view them.
- Before you put a screenshot in an article, on social media, or in a shared internal deck, make sure no stock price is visible.
- Keep the proxy on `127.0.0.1` so no one else can connect.

Gate the quote behind an explicit "private display" switch so it never slips into a public page by accident:

```python
SHOW_QUOTE = os.environ.get("ZENITH_PRIVATE_QUOTE") == "1"  # set to 1 only on your own machine

# inside do_POST, in place of self.reply(200, {...})
body = {"symbol": symbol, "rows": rows}
if SHOW_QUOTE:
    quote = call_zenith(api_key, "/quote", {"symbol": symbol})
    latest = quote[0] if quote else None
    body["privateQuote"] = {"price": latest["price"], "priceDate": latest["priceDate"]} if latest else None
self.reply(200, body)
```

On screen, label the price area "shown in a private environment only."

The price date and the fiscal period are different points in time. `priceDate` is the latest trading day; `fiscalPeriod` is the month the fiscal period ended. If you combine a current price with past results to compute your own metrics, keep the timing gap in mind. Check the display rules before showing any price-derived value on a public page.

See [What you can and can't display](https://zenithcode.net/en/docs/display-rights) for the full rules.

## Read the numbers carefully

- **Amounts are in yen; ratios are decimals from 0 to 1.** Operating margin is 0.0998 in the API and 9.98% on screen.
- **An empty array means no reported results.** Newly listed companies may have no annual rows yet, and pre-listing income statements may not be available.
- **Values can change later.** Corrections, or replacing earnings-summary figures with securities-report figures, update the same period. When you compare with a known value, compare the filing ID too.
- **Non-yen periods have `null` amounts.** US dollar reporters (6269 and 9399) return `nullReason` of `non_jpy_material`.
- **Timestamps are UTC.** Convert `announcedAt` and `updatedAt` to Japan time before display.
- **Price dates and fiscal periods differ.** Don't line up today's price and a fiscal year that ended months ago as if they were the same moment.

## Summary

- Keep the API key out of the browser; only the local proxy holds it, read from an environment variable or a hidden prompt.
- Bind the proxy to `127.0.0.1`, check `Host`, `Origin`, and a startup token, and accept only the specific request you need.
- Don't relay upstream error bodies, and validate the response shape before display.
- After switching to live data, check a known value, units, missing values, and sources. Show stock prices only in your private environment.

## Related

- [Income statement API docs](https://zenithcode.net/en/docs/income-statement)
- [Quote API docs](https://zenithcode.net/en/docs/quote)
- [What you can and can't display](https://zenithcode.net/en/docs/display-rights)
- [Track the source of every financial figure](https://zenithcode.net/en/docs/cookbook/applied/practice-statements-and-sources)
- [Display rules for financial tables and charts](https://zenithcode.net/en/docs/cookbook/applied/practice-responsive-layout)
- [Sample code repository (server.py in the company-analysis template)](https://github.com/Crab-grass/zenith-code-examples/tree/main/templates/company-analysis)

A Japanese-language walkthrough with screenshots is on [Qiita](https://qiita.com/Sohei-Taniguchi-CG/items/6f927c65172a28401525).

---
Page: https://zenithcode.net/en/docs/cookbook/applied/practice-live-data
日本語: https://zenithcode.net/docs/cookbook/applied/practice-live-data.md
Site guide for AI tools: https://zenithcode.net/llms.txt
