Client libraries

Dependency-free JavaScript and Python clients for the DistrictFacts API.

No official DistrictFacts client library is published. These complete dependency-free JavaScript and Python clients support an optional key, the index, district directories, district records, bounded 429 retry, and bulk redirects. A keyed bulk GET returns 302 with a Location signed for ten minutes; the clients fetch it separately without forwarding Authorization.

JavaScript

export class DistrictFacts {
  constructor({ base = "https://www.districtfacts.com", key } = {}) {
    this.base = base.replace(/\/$/, "");
    this.key = key;
  }
  async get(path, attempt = 0) {
    const headers = this.key ? { Authorization: `Bearer ${this.key}` } : {};
    const response = await fetch(this.base + path, { headers });
    if (response.status === 429 && attempt < 4) {
      const wait = Number(response.headers.get("retry-after") ?? 1);
      await new Promise(resolve => setTimeout(resolve, wait * 1000));
      return this.get(path, attempt + 1);
    }
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json();
  }
  index() { return this.get("/data/v1/index.json"); }
  districts(state) { return this.get(`/data/v1/${state}/districts.json`); }
  district(state, slug) {
    return this.get(`/data/v1/${state}/districts/${slug}.json`);
  }
  async bulk(state) {
    const path = `/data/v1/${state}/bulk.ndjson`;
    if (!this.key) return fetch(this.base + path);
    const first = await fetch(this.base + path, {
      headers: { Authorization: `Bearer ${this.key}` }, redirect: "manual"
    });
    if (first.status !== 302) throw new Error(`HTTP ${first.status}`);
    const location = first.headers.get("location");
    if (!location) throw new Error("Missing Location");
    return fetch(location); // Never forward Authorization to the signed URL.
  }
}

const api = new DistrictFacts();
console.log(await api.index());

Python

import json
import time
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from urllib.request import HTTPRedirectHandler, build_opener

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl): return None

class DistrictFacts:
    def __init__(self, base="https://www.districtfacts.com", key=None):
        self.base = base.rstrip("/")
        self.key = key

    def get(self, path, attempt=0):
        headers = {"Authorization": f"Bearer {self.key}"} if self.key else {}
        request = Request(self.base + path, headers=headers)
        try:
            with urlopen(request, timeout=30) as response:
                return json.load(response)
        except HTTPError as error:
            if error.code == 429 and attempt < 4:
                time.sleep(int(error.headers.get("Retry-After", "1")))
                return self.get(path, attempt + 1)
            raise

    def index(self): return self.get("/data/v1/index.json")
    def districts(self, state): return self.get(f"/data/v1/{state}/districts.json")
    def district(self, state, slug):
        return self.get(f"/data/v1/{state}/districts/{slug}.json")

    def bulk(self, state):
        path = f"/data/v1/{state}/bulk.ndjson"
        if not self.key: return urlopen(self.base + path, timeout=60)
        request = Request(self.base + path,
            headers={"Authorization": f"Bearer {self.key}"})
        try: build_opener(NoRedirect).open(request)
        except HTTPError as response:
            if response.code != 302: raise
            location = response.headers["Location"]
        return urlopen(location, timeout=60)  # No Authorization header.

api = DistrictFacts()
print(json.dumps(api.index(), indent=2))

Developer documentation