> **Sole author and operator (personal open-source project)** · February 2024 to present
> Source: https://www.simonbetton.com/case-studies/ratesapi.md (markdown only; there is no HTML page for this document).
> Index of case studies: https://www.simonbetton.com/case-studies/index.md

# Case study: Rates API, a public JSON API of New Zealand lending rates

## Quick facts

|  |  |
| --- | --- |
| **Role** | Sole author and operator (personal open-source project) |
| **Product** | Rates API at ratesapi.nz, MIT, public on GitHub |
| **Timeline** | February 2024 to present; replatformed 30 April 2026 |
| **Team** | One person across collection, API, docs, and operations |
| **Stack** | Bun, TypeScript, Elysia, TypeBox, Cloudflare Workers, D1, Wrangler, Cheerio, Scalar, Biome; docs on Next.js and Fumadocs |
| **Surface** | 13 versioned GET routes, 12 MCP tools, OpenAPI 3.0.3, llms.txt |
| **Data** | 36 mortgage lenders, 39 personal-loan lenders, 32 car-loan lenders, 33 card issuers in the live snapshots as of September 2026 |

## Overview

Rates API publishes mortgage, personal loan, car loan, and credit card rates from New Zealand lenders as stable JSON. There is no signup and no key. The first request can be a real GET, and the same lookups are available to AI agents over the Model Context Protocol.

It is infrastructure rather than a comparison site. The intended users already know what they want to build: repayment calculators, market dashboards, research notebooks, and assistants that need a live rate rather than a guessed one.

I started it in February 2024 and have run it alone since. The service that exists today is the result of two phases: two years of scraping, storage, and history on a Hono Worker, and a replatform on 30 April 2026 onto Elysia with contract tests, a separate docs app, and an MCP endpoint that had landed two months earlier.

## The problem

New Zealand lending rates live on public pages that change layout, labels, and product names. Anyone building a calculator or comparison table ends up scraping those pages and rediscovering the same bugs: colspan cells, renamed "special" products, institutions that appear and disappear, and dates that pass a regex but are not real calendar days.

The problem sharpened once coding agents and chat assistants started answering rate questions. An agent that browses a lender site is slow, brittle, and hard to audit; one that calls a typed tool with a stable institution ID can ground an answer in data you can log.

I wanted one public service that collects on a schedule instead of at request time, normalises messy HTML into identifiers that survive copy changes, serves the same lookup through REST and MCP, publishes a machine-readable contract, and costs almost nothing to keep online. Constraints I accepted: no accounts, no API keys, CORS open to any origin, MIT licence, and a budget that only makes sense on a serverless edge runtime with a free scheduler.

## How the service works

```
interest.co.nz aggregator tables
        │  hourly GitHub Actions cron (Cheerio scrapers, one per family)
        │  validate against the API's own schemas → skip write if unchanged
        ▼
Cloudflare D1
  latest_data       one base64 JSON blob per family + last_updated
  historical_data   one blob per family per calendar day (later scrape replaces)
        ▼
Cloudflare Worker (Elysia)            Docs Worker (Next.js + Fumadocs)
  /api/v1/{family}            list      ratesapi.nz  22 pages, llms.txt
  /api/v1/{family}/{id}       one lender
  /api/v1/{family}/time-series
  /api/v1/health              freshness per dataset
  /api/v1/mcp                 JSON-RPC, 12 tools
  /openapi, /openapi/json     Scalar UI + generated spec
        ▲
GitHub Actions uptime cron: 21 URLs every 15 minutes → issue on failure
```

The Worker never scrapes at request time: collection runs in GitHub Actions and writes through Wrangler, and the Worker only reads D1.

## Decisions and trade-offs

Snapshots are whole documents rather than one row per rate. D1 holds base64-encoded JSON blobs, one per family for the latest state and one per family per day for history. Hourly writes and "skip if unchanged" are cheap because each scraper compares the new payload to the current one and writes nothing when they match. The cost is that filters run in process after parsing the blob. I would not pick this if queries needed SQL-side joins; for "today's mortgages, optionally by term" it is enough.

History is daily even though collection is hourly: a later scrape on the same calendar day replaces that day's row, so intra-day moves are not a time series. Freshness is exposed instead through the health endpoint, which reports the last time each dataset changed. That is a change timestamp, not a scrape timestamp: a dataset whose rates have not moved keeps an old value even while collection runs.

REST and MCP share lookup logic. The MCP handler imports the same query functions the route modules use and wraps the JSON as MCP text content, so an invalid filter fails the same way on both surfaces and there is one place to fix a date bug.

MCP stays out of the OpenAPI document, which describes REST. MCP is JSON-RPC 2.0 over a single POST, protocol version 2024-11-05, with initialize, ping, tool listing, and tool call. Mixing it into generated REST clients would produce junk SDKs, so the spec excludes that path and a contract test asserts the exclusion. The endpoint is hand-written because the Worker needs only those four methods; parse errors return -32700, unknown methods -32601, bad parameters -32602, and lookup failures return MCP content with an error flag so the caller still gets a readable body.

Identifiers are slug-shaped and prefixed: institution, product, and rate IDs for loans; issuer and plan IDs for cards, because that is how the card market talks. The path grammar is the same across the four families, so a consumer UI can template routes and an agent can reuse an ID from one call in the next.

Dates are strict. Time-series dates must be real UTC calendar days, not just a matching pattern, and a caller passes either a single date or a start and end pair; mixing the two shapes returns 400 with a stable code and message. Unknown query parameters are ignored rather than rejected.

The upstream is named. Every rates response carries a terms-of-use string that says the data comes from interest.co.nz hourly, is not guaranteed accurate, and should be checked with the lender. Selectors and column positions on those aggregator tables are the hard dependency of the whole service; the mortgage scraper carries a list of known label variants for "special" products and handles the colspan rows the tables use for them.

## The 2026 replatform

The service ran on Hono, with a zod-based OpenAPI layer and ESLint, from February 2024 until 30 April 2026. Before March 2025 the scrapers committed JSON files into the repository itself, and a GitHub Actions bot made 447 of the repository's commits doing so. D1-backed history arrived in March 2025, an uptime check in April 2025, and the MCP endpoint on 2 February 2026, still on Hono.

On 30 April 2026 I replaced Hono with Elysia and TypeBox, and ESLint with Biome, in one pull request that also added the contract test suite and the pinned agent skills. The test names say what the suite was for: "returns the existing successful list shape", "keeps mortgage term filtering shape unchanged", "leaves documentation pages to the docs app". The intent was to lock the public shapes before the framework under them moved. I did not diff live responses across the cutover.

What the move bought is that the same TypeBox objects now validate requests, scraper output, and responses, and generate the served OpenAPI document, so the Scalar UI and any generated client describe what production returns. The cost was a full rewrite of a small codebase on a live public API, mitigated by the dry-run deploy and the contract suite. The same day, thirty-odd further commits moved documentation out of the Worker into a Next.js and Fumadocs app on its own Worker, added CI checks with a dry-run deploy, and added a Fallow job; most of those were written by a Cursor agent in pull requests I reviewed and merged.

## Operations

Collection is a GitHub Actions cron every hour, also on push to main. It runs lint, typecheck, and tests first, verifies D1 access, runs the four scrapers, and lists the saved rows. Each scraper loads the current snapshot, validates the new one against the API's schemas, and skips the write when nothing changed.

An uptime workflow requests 21 production URLs every 15 minutes: the four lists, four single-lender reads, health, four time-series endpoints, four filtered time-series, and four date-filtered variants. It retries 500-class responses three times and, on failure, opens a GitHub issue labelled as an incident. Seven incident issues are recorded, all in 2026 and all closed; five of them fell in August 2026.

Deploys happen on push to main after the same checks, for the API Worker and the docs Worker. Pull requests also run a dry-run Wrangler deploy so a broken config never waits for production, and a Fallow static-analysis job that reports but does not fail the build.

## Technologies and standards

| Layer | Choices |
| --- | --- |
| Runtime | Bun, TypeScript (strict, no unchecked index access, no unused locals), Cloudflare Workers and D1, Wrangler |
| HTTP | Elysia, TypeBox schemas, @elysia/openapi, Scalar UI |
| Collection | Cheerio scrapers in GitHub Actions, skip write if unchanged |
| Docs | Next.js on OpenNext for Cloudflare, Fumadocs, 22 MDX pages, llms.txt route |
| Quality | Biome with cognitive complexity as an error, Husky pre-commit running the tests, contract tests on a D1 mock, dry-run deploy, Fallow (non-blocking), Dependabot weekly |
| Agent surfaces | OpenAPI 3.0.3, Model Context Protocol 2024-11-05 over JSON-RPC 2.0, llms.txt |
| Contract details | CORS any origin with 600-second preflight cache, UUID request IDs echoed or generated, ISO 8601 timestamps, ISO calendar dates, MIT licence |

## How AI was used

There is no generative model in collection or serving. Rates are scraped, validated, stored, and returned. The product is something agents call, not an agent.

In development I use coding agents as contributors: 22 commits between February and May 2026 are authored by a Cursor agent, including the MCP endpoint (merged 3 February 2026 from an agent branch), the docs-app migration, the CI and Fallow workflows, and the development-only fallback to production data. The Hono-to-Elysia commit, the contract tests, and the D1 history work are mine. Where an agent wrote the code, the contract tests and the typecheck are what let me accept it.

Eleven agent skills are pinned in a lockfile with content hashes, added with the replatform: test-driven vertical slices, grilling a plan one question at a time, a diagnosis loop, issue triage, turning conversations into PRDs and issues, and architecture review for deep modules, plus the Fallow skill. Fallow is also exposed to the editor over MCP so an agent can inspect structure before editing. I do not let an agent invent the HTTP contract: the schemas and contract tests are the source of truth. The repository still has no domain glossary or ADRs even though the architecture skill expects them, which is a gap.

## What I can and cannot claim

| Measure | Value |
| --- | --- |
| Public product | ratesapi.nz, MIT, no API key, live since 2024 |
| Coverage in the live snapshots | 36 mortgage lenders; 39 personal-loan lenders; 32 car-loan lenders; 33 card issuers |
| Versioned REST GETs | 13 (three per family plus health); 13 paths in the served OpenAPI document |
| MCP tools | 12 |
| Tests | 27 across three files, 105 assertions, all passing |
| Uptime loop | 21 URLs every 15 minutes; 7 incident issues opened, all closed |
| Repository | 647 commits on the public branch: 447 by the data bot before March 2025, 171 by me, 22 by a Cursor agent, the rest by Dependabot |

I have no request-volume or consumer figures and will not estimate them. What the choices did produce is observable: a consumer can template four product families from one route grammar, an agent can call production without a secrets manager, scrapers cannot publish a shape the API will not serve because they share its schemas, and the public contract was written down as tests before the framework under it was replaced.
