Skip to content

API Reference

Generated reference for the RepeaterBook Python Client.

Rendering options are configured globally in mkdocs.yml, so each section below just names the module it documents.

Package exports

The names re-exported at the top level: the Repeater model, the RepeaterBook database handle, and the exception hierarchy. Everything else is imported from its own module.

repeaterbook

Unofficial third-party Python client for the RepeaterBook.com API.

Classes

RepeaterBook

Local database for repeater data from the RepeaterBook.com API.

This file is a cache, not durable storage. It holds nothing that cannot be re-downloaded from RepeaterBook, so when the schema in code no longer matches the schema the file was written with, the file is discarded and rebuilt rather than migrated. Keep your own data somewhere else.

The underlying engine and its connection pool are created lazily on first use and live until close() is called, so use the instance as a context manager (or call close() yourself) to release the SQLite handle when you are done. Closing is optional: an instance that is never closed still works, and its connections are finalized when it is garbage collected.

Attributes
database_path property
database_path: Path

Database path.

database_uri property
database_uri: str

Database URI.

engine cached property
engine: Engine

Create database engine, discarding the file if its schema is stale.

The check lives here rather than in init_db because reading from a stale file has to be caught too, and query never calls init_db. This is the one path every caller goes through.

Functions
close
close() -> None

Dispose of the engine and release its pooled SQLite connections.

The instance stays usable: the next access to engine (directly or via populate, query or truncate) builds a fresh one, re-running the staleness check. Calling this on an instance whose engine was never built, or that is already closed, is a no-op.

Any Session you built against the old engine yourself is not tracked here; close those first.

Source code in src/repeaterbook/database.py
def close(self) -> None:
    """Dispose of the engine and release its pooled SQLite connections.

    The instance stays usable: the next access to `engine` (directly or
    via `populate`, `query` or `truncate`) builds a fresh one, re-running
    the staleness check. Calling this on an instance whose engine was
    never built, or that is already closed, is a no-op.

    Any `Session` you built against the old `engine` yourself is not
    tracked here; close those first.
    """
    # `attrs.frozen` makes the class slotted, so the cached engine lives in
    # a slot rather than `__dict__`, and `del self.engine` is refused by
    # the frozen `__delattr__`. Going through `object` bypasses both the
    # freeze and attrs' lazy-building `__getattr__`: an empty slot raises
    # rather than constructing an engine only to throw it away.
    try:
        engine: Engine = object.__getattribute__(self, "engine")
    except AttributeError:
        return
    object.__delattr__(self, "engine")
    engine.dispose()
    logger.debug(f"Closed database at {self.database_path}.")
init_db
init_db() -> None

Initialize database, recording the schema it was created with.

Kept as public API, but building the engine already does this, so it is a no-op on an engine that has been touched.

Source code in src/repeaterbook/database.py
def init_db(self) -> None:
    """Initialize database, recording the schema it was created with.

    Kept as public API, but building the engine already does this, so it
    is a no-op on an engine that has been touched.
    """
    SQLModel.metadata.create_all(self.engine)
    self._record_fingerprint(self.engine)
populate
populate(repeaters: Iterable[Repeater]) -> None

Populate internal database.

Source code in src/repeaterbook/database.py
def populate(self, repeaters: Iterable[Repeater]) -> None:
    """Populate internal database."""
    self.init_db()

    with Session(self.engine) as session:
        for repeater in repeaters:
            session.merge(repeater)
        session.commit()

    logger.info("Populated repeaters.")
query
query(*where: _ColumnExpressionArgument[bool] | bool) -> Sequence[Repeater]

Query the database.

Source code in src/repeaterbook/database.py
def query(
    self,
    *where: _ColumnExpressionArgument[bool] | bool,
) -> Sequence[Repeater]:
    """Query the database."""
    with Session(self.engine) as session:
        statement = select(Repeater).where(*where)
        repeaters = session.exec(statement).all()

    logger.info(f"Found {len(repeaters)} repeaters.")

    return repeaters
truncate
truncate() -> int

Delete every repeater, leaving the file and its schema marker in place.

This empties the data without making the file look stale: the next open finds a current, empty database rather than one to discard. It does not touch the API response cache, which RepeaterBookAPI owns; a populate shortly after a truncate may therefore be served from that cache rather than the network.

Returns:

Type Description
int

The number of repeaters removed.

Source code in src/repeaterbook/database.py
def truncate(self) -> int:
    """Delete every repeater, leaving the file and its schema marker in place.

    This empties the data without making the file look stale: the next open
    finds a current, empty database rather than one to discard. It does
    not touch the API response cache, which `RepeaterBookAPI` owns; a
    `populate` shortly after a truncate may therefore be served from that
    cache rather than the network.

    Returns:
        The number of repeaters removed.
    """
    with Session(self.engine) as session:
        removed = session.exec(delete(Repeater)).rowcount
        session.commit()

    logger.info(f"Truncated {removed} repeaters.")
    return removed

RepeaterBookAPIError

RepeaterBookAPIError(message: str, *, status_code: int | None = None, error_code: str | None = None, url: str | None = None, body: object | None = None)

Bases: RepeaterBookError

Error returned by the RepeaterBook API.

Raised when the API returns an error response (status: "error"). The error message from the API is preserved in the exception message.

Initialize an API error with optional structured response context.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    error_code: str | None = None,
    url: str | None = None,
    body: object | None = None,
) -> None:
    """Initialize an API error with optional structured response context."""
    self.message = message
    self.status_code = status_code
    self.error_code = error_code
    self.url = url
    self.body = body
    super().__init__(message)

RepeaterBookCacheError

Bases: RepeaterBookError

Error during cache operations.

Raised when reading from or writing to the cache fails, such as file permission issues or disk full errors.

RepeaterBookError

Bases: Exception

Base exception for the RepeaterBook Python Client.

All RepeaterBook Python Client exceptions inherit from this class, making it easy to catch all library errors with a single except clause.

RepeaterBookForbiddenError

RepeaterBookForbiddenError(message: str, *, status_code: int | None = None, error_code: str | None = None, url: str | None = None, body: object | None = None)

Bases: RepeaterBookAPIError

Authenticated but not authorized to access the API.

Raised when the API returns a 403 Forbidden status code, such as when User-Agent policy enforcement or an authorization scope denies access.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    error_code: str | None = None,
    url: str | None = None,
    body: object | None = None,
) -> None:
    """Initialize an API error with optional structured response context."""
    self.message = message
    self.status_code = status_code
    self.error_code = error_code
    self.url = url
    self.body = body
    super().__init__(message)

RepeaterBookRateLimitError

RepeaterBookRateLimitError(message: str, *, retry_after: float | None = None, **kwargs: Unpack[_APIErrorContext])

Bases: RepeaterBookAPIError

API request rejected because the rate limit was exceeded.

Raised when the API returns a 429 Too Many Requests status code.

Initialize a rate-limit error with an optional retry delay.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    retry_after: float | None = None,
    **kwargs: Unpack[_APIErrorContext],
) -> None:
    """Initialize a rate-limit error with an optional retry delay."""
    super().__init__(message, **kwargs)
    self.retry_after = retry_after

RepeaterBookRowError

RepeaterBookRowError(message: str, *, row: object | None = None, label: str | None = None)

Bases: RepeaterBookValidationError

A single export row could not be converted into a Repeater.

RepeaterBook data is community-maintained, so individual rows are occasionally unmodellable (a zero input frequency, an out-of-range coordinate, a missing frequency). This wraps the underlying parse or validation failure together with the offending row, so a caller can tell which record failed and why.

By default RepeaterBookAPI.download logs and skips these rather than raising, so one bad row cannot discard an otherwise good response. Pass strict=True to have them propagate instead.

Attributes:

Name Type Description
row

The raw export row that failed to convert.

label

Best-effort identifier for the row, e.g. "48:24371 (W5AW)".

Initialize a row error with the offending row and its label.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    row: object | None = None,
    label: str | None = None,
) -> None:
    """Initialize a row error with the offending row and its label."""
    self.message = message
    self.row = row
    self.label = label
    super().__init__(message)

RepeaterBookUnauthorizedError

RepeaterBookUnauthorizedError(message: str, *, status_code: int | None = None, error_code: str | None = None, url: str | None = None, body: object | None = None)

Bases: RepeaterBookAPIError

Unauthorized access to the API.

Raised when the API returns a 401 Unauthorized status code, indicating that authentication is required or has failed.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    error_code: str | None = None,
    url: str | None = None,
    body: object | None = None,
) -> None:
    """Initialize an API error with optional structured response context."""
    self.message = message
    self.status_code = status_code
    self.error_code = error_code
    self.url = url
    self.body = body
    super().__init__(message)

RepeaterBookValidationError

Bases: RepeaterBookError

Invalid data or response format.

Raised when: - API response is not in expected format (not a dict) - Required fields are missing from the response - Data values fail validation (e.g., invalid coordinates)

Repeater

Bases: SQLModel

Repeater.

Attributes
fm property
fm: FmParams | None

FM parameters, or None if not FM-capable.

dmr property
dmr: DmrParams | None

DMR parameters, or None if not DMR-capable.

dstar property
dstar: DStarParams | None

D-STAR parameters, or None if not D-STAR-capable.

fusion property
fusion: FusionParams | None

System Fusion parameters, or None if not Fusion-capable.

p25 property
p25: P25Params | None

P25 parameters, or None if not P25-capable.

nxdn property
nxdn: NxdnParams | None

NXDN parameters, or None if not NXDN-capable.

tetra property
tetra: TetraParams | None

TETRA parameters, or None if not TETRA-capable.

m17 property
m17: M17Params | None

M17 parameters, or None if not M17-capable.

modes property
modes: frozenset[RepeaterMode]

The set of modes this repeater supports.

emergency_services property
emergency_services: frozenset[Emergency]

The emergency services this repeater is known to support.

Mirrors modes, and uses the same Emergency enum that ExportQuery.emergency_services uses to ask for these repeaters, so the query and result sides speak one vocabulary.

Only True counts. An unknown service (None, i.e. a rest-of-world export that never reported it) is omitted just like an unsupported one, so an empty set means "none known", not "none supported". Read the individual fields when that difference matters.

Functions
validate_latitude classmethod
validate_latitude(v: Decimal) -> Decimal

Validate latitude is within valid range.

Source code in src/repeaterbook/models.py
@field_validator("latitude")
@classmethod
def validate_latitude(cls, v: Decimal) -> Decimal:
    """Validate latitude is within valid range."""
    if not Decimal(-90) <= v <= Decimal(90):
        msg = f"Latitude must be between -90 and 90, got {v}"
        raise ValueError(msg)
    return v
validate_longitude classmethod
validate_longitude(v: Decimal) -> Decimal

Validate longitude is within valid range.

Source code in src/repeaterbook/models.py
@field_validator("longitude")
@classmethod
def validate_longitude(cls, v: Decimal) -> Decimal:
    """Validate longitude is within valid range."""
    if not Decimal(-180) <= v <= Decimal(180):
        msg = f"Longitude must be between -180 and 180, got {v}"
        raise ValueError(msg)
    return v
validate_frequency classmethod
validate_frequency(v: Decimal) -> Decimal

Validate frequency is positive.

Source code in src/repeaterbook/models.py
@field_validator("frequency", "input_frequency")
@classmethod
def validate_frequency(cls, v: Decimal) -> Decimal:
    """Validate frequency is positive."""
    if v <= 0:
        msg = f"Frequency must be positive, got {v}"
        raise ValueError(msg)
    return v

Models

The Repeater ORM row, the API's JSON TypedDicts, and ExportQuery.

repeaterbook.models

Models.

Attributes

BOOL_MAP module-attribute

BOOL_MAP: Final[dict[str | int, bool]] = {'Yes': True, 'No': False, 1: True, 0: False}

RepeaterBook's boolean vocabulary, stated once.

The JSON export mixes the "Yes"/"No" strings with 1/0 integers (Precise is the integer one); the CSV export uses the strings only. Both ingest paths decode through parse_flag and parse_yes_no, so this is the single place that spells out what a truthy or falsy cell looks like on the wire.

Deliberately not in here: the CSV's blank cell, which that export uses where the JSON would say "No". parse_flag reads a blank as its default, and parse_yes_no must keep reading it as unknown; an "": False entry would break the second to spare the first a keyword argument.

Classes

Status

Bases: Enum

Status.

Use

Bases: Enum

Use.

Mode

Bases: Enum

Mode.

Emergency

Bases: Enum

Emergency.

ServiceType

Bases: Enum

Service type.

Repeater

Bases: SQLModel

Repeater.

Attributes
fm property
fm: FmParams | None

FM parameters, or None if not FM-capable.

dmr property
dmr: DmrParams | None

DMR parameters, or None if not DMR-capable.

dstar property
dstar: DStarParams | None

D-STAR parameters, or None if not D-STAR-capable.

fusion property
fusion: FusionParams | None

System Fusion parameters, or None if not Fusion-capable.

p25 property
p25: P25Params | None

P25 parameters, or None if not P25-capable.

nxdn property
nxdn: NxdnParams | None

NXDN parameters, or None if not NXDN-capable.

tetra property
tetra: TetraParams | None

TETRA parameters, or None if not TETRA-capable.

m17 property
m17: M17Params | None

M17 parameters, or None if not M17-capable.

modes property
modes: frozenset[RepeaterMode]

The set of modes this repeater supports.

emergency_services property
emergency_services: frozenset[Emergency]

The emergency services this repeater is known to support.

Mirrors modes, and uses the same Emergency enum that ExportQuery.emergency_services uses to ask for these repeaters, so the query and result sides speak one vocabulary.

Only True counts. An unknown service (None, i.e. a rest-of-world export that never reported it) is omitted just like an unsupported one, so an empty set means "none known", not "none supported". Read the individual fields when that difference matters.

Functions
validate_latitude classmethod
validate_latitude(v: Decimal) -> Decimal

Validate latitude is within valid range.

Source code in src/repeaterbook/models.py
@field_validator("latitude")
@classmethod
def validate_latitude(cls, v: Decimal) -> Decimal:
    """Validate latitude is within valid range."""
    if not Decimal(-90) <= v <= Decimal(90):
        msg = f"Latitude must be between -90 and 90, got {v}"
        raise ValueError(msg)
    return v
validate_longitude classmethod
validate_longitude(v: Decimal) -> Decimal

Validate longitude is within valid range.

Source code in src/repeaterbook/models.py
@field_validator("longitude")
@classmethod
def validate_longitude(cls, v: Decimal) -> Decimal:
    """Validate longitude is within valid range."""
    if not Decimal(-180) <= v <= Decimal(180):
        msg = f"Longitude must be between -180 and 180, got {v}"
        raise ValueError(msg)
    return v
validate_frequency classmethod
validate_frequency(v: Decimal) -> Decimal

Validate frequency is positive.

Source code in src/repeaterbook/models.py
@field_validator("frequency", "input_frequency")
@classmethod
def validate_frequency(cls, v: Decimal) -> Decimal:
    """Validate frequency is positive."""
    if v <= 0:
        msg = f"Frequency must be positive, got {v}"
        raise ValueError(msg)
    return v

ExportJSON

Bases: TypedDict

RepeaterBook API export response.

ExportErrorJSON

Bases: TypedDict

RepeaterBook API export error response.

ExportBaseQuery

Bases: TypedDict

RepeaterBook API export query.

% - wildcard

Attributes
callsign instance-attribute
callsign: list[str]

Repeater callsign.

city instance-attribute
city: list[str]

Repeater city.

country instance-attribute
country: list[str]

Repeater country.

frequency instance-attribute
frequency: list[str]

Repeater frequency.

mode instance-attribute
mode: list[ModeJSON]

Repeater operating mode (analog, DMR, NXDN, P25, tetra).

ExportNorthAmericaQuery

Bases: ExportBaseQuery

RepeaterBook API export North America query.

% - wildcard

Attributes
state_id instance-attribute
state_id: list[str]

State / province.

county instance-attribute
county: list[str]

Repeater county.

emcomm instance-attribute
emcomm: list[EmergencyJSON]

ARES, RACES, SKYWARN, CANWARN.

stype instance-attribute
stype: list[ServiceTypeJSON]

Service type. Only required when searching for GMRS repeaters.

ExportWorldQuery

Bases: ExportBaseQuery

RepeaterBook API export World query.

% - wildcard

Attributes
region instance-attribute
region: list[str]

Repeater region (if available).

ExportQuery

RepeaterBook API export query.

% - wildcard

Functions

parse_flag

parse_flag(raw: object, *, default: bool = False) -> bool

Decode a two-state capability flag such as DMR or FM Analog.

These fields are "does this repeater do X", where the export has no way to say "unknown": a repeater either has the capability or it doesn't. So unlike the tri-state parse_yes_no, anything unrecognized collapses to default, and the answer is always a bool.

  • "Yes" or 1 -> True.
  • "No" or 0 -> False.
  • None, "", whitespace, or any unrecognized string -> default.

The two exports disagree on the negative case. JSON sends the literal "No"; the CSV leaves the cell blank. Both land on False here: "No" through the vocabulary, blank through default. That is deliberate -- the blank-means-no convention is the CSV's, and the decoder relies on default for it rather than a second spelling in BOOL_MAP.

Surrounding whitespace is stripped from strings, matching parse_yes_no. Matching is case-sensitive: RepeaterBook only ever sends "Yes"/"No", so a differently-cased value is unrecognized rather than reinterpreted.

Parameters:

Name Type Description Default
raw object

The cell as the export delivered it.

required
default bool

What an absent, blank, or unrecognized cell decodes to.

False

Returns:

Type Description
bool

The decoded flag.

Raises:

Type Description
TypeError

If raw is neither a string, an integer, nor None. A list or a dict in a boolean field is a malformed row, not a missing value, and should be reported as such rather than silently defaulted.

Source code in src/repeaterbook/models.py
def parse_flag(raw: object, *, default: bool = False) -> bool:
    """Decode a two-state capability flag such as `DMR` or `FM Analog`.

    These fields are "does this repeater do X", where the export has no way
    to say "unknown": a repeater either has the capability or it doesn't. So
    unlike the tri-state `parse_yes_no`, anything unrecognized collapses to
    `default`, and the answer is always a `bool`.

    - `"Yes"` or `1` -> `True`.
    - `"No"` or `0` -> `False`.
    - `None`, `""`, whitespace, or any unrecognized string -> `default`.

    The two exports disagree on the negative case. JSON sends the literal
    `"No"`; the CSV leaves the cell blank. Both land on `False` here: `"No"`
    through the vocabulary, blank through `default`. That is deliberate --
    the blank-means-no convention is the CSV's, and the decoder relies on
    `default` for it rather than a second spelling in `BOOL_MAP`.

    Surrounding whitespace is stripped from strings, matching `parse_yes_no`.
    Matching is case-sensitive: RepeaterBook only ever sends `"Yes"`/`"No"`,
    so a differently-cased value is unrecognized rather than reinterpreted.

    Args:
        raw: The cell as the export delivered it.
        default: What an absent, blank, or unrecognized cell decodes to.

    Returns:
        The decoded flag.

    Raises:
        TypeError: If `raw` is neither a string, an integer, nor `None`. A
            list or a dict in a boolean field is a malformed row, not a
            missing value, and should be reported as such rather than
            silently defaulted.
    """
    if raw is None:
        return default
    if isinstance(raw, bool):
        # bool subclasses int, so True/False would otherwise fall through to
        # the integer lookup and resolve via `1`/`0`. Accept them directly;
        # the export never sends them, but nothing is gained by refusing.
        return raw
    if isinstance(raw, str):
        return BOOL_MAP.get(raw.strip(), default)
    if isinstance(raw, int):
        return BOOL_MAP.get(raw, default)
    msg = f"Invalid type for boolean field: {type(raw)}"
    raise TypeError(msg)

parse_yes_no

parse_yes_no(raw: object) -> bool | None

Decode RepeaterBook's "Yes"/"No" vocabulary into a tri-state boolean.

The emergency-service fields are genuinely three-valued, which is why this returns None rather than defaulting to False the way parse_flag does for the capability flags:

  • "Yes" -> True, the service is supported.
  • "No" -> False, the service is explicitly not supported.
  • missing, empty, or unrecognized -> None, unknown.

The third state is not hypothetical: exportROW.php omits these keys entirely, so every rest-of-world repeater is unknown rather than unsupported. Collapsing unknown into False would assert something the export never said.

Only the string half of BOOL_MAP applies. These four fields never use the 1/0 spelling, so an integer here is unrecognized, not a yes or no.

Source code in src/repeaterbook/models.py
def parse_yes_no(raw: object) -> bool | None:
    """Decode RepeaterBook's `"Yes"`/`"No"` vocabulary into a tri-state boolean.

    The emergency-service fields are genuinely three-valued, which is why this
    returns `None` rather than defaulting to `False` the way `parse_flag`
    does for the capability flags:

    - `"Yes"` -> `True`, the service is supported.
    - `"No"` -> `False`, the service is explicitly *not* supported.
    - missing, empty, or unrecognized -> `None`, **unknown**.

    The third state is not hypothetical: `exportROW.php` omits these keys
    entirely, so every rest-of-world repeater is unknown rather than
    unsupported. Collapsing unknown into `False` would assert something the
    export never said.

    Only the string half of `BOOL_MAP` applies. These four fields never use
    the `1`/`0` spelling, so an integer here is unrecognized, not a yes or no.
    """
    if isinstance(raw, str):
        return BOOL_MAP.get(raw.strip())
    return None

Services

The API client, HTTP caching, endpoint routing, and JSON → model conversion.

repeaterbook.services

Services.

Classes

RepeaterBookAPI

Unofficial client for the RepeaterBook.com API.

Must read https://repeaterbook.com/wiki/doku.php?id=api before using.

Live exports need a per-user rbuapp_ token. No application registration is required: this library is registered with RepeaterBook as "RepeaterBook Python Client" (App #114), so log in to your RepeaterBook account, open https://www.repeaterbook.com/user/api_apps.php, find App #114, and generate a token for it. The default app_name/app_version/app_contact are the identity approved for that application, so a token generated this way works without further configuration.

Attributes:

Name Type Description
base_url URL

The RepeaterBook API base URL.

app_name str

Application name for User-Agent header. Leave at the default unless you registered your own application with RepeaterBook.

app_version str

Application version for User-Agent header. Leave at the default unless you registered your own application.

app_contact str

Contact information for User-Agent header. Leave at the default unless you registered your own application -- the API matches an approved application's User-Agent literally, so setting this to your own address returns 403 ua_mismatch.

app_token SecretStr | None

Optional per-user RepeaterBook API token, sent via the X-RB-App-Token header. Live exports require an approved rbuapp_ token as of RepeaterBook's 2026-03-03 API policy. Held as a SecretStr so it is masked in reprs and logs; a plain str is accepted and wrapped.

working_dir Path

Directory for cache and database files.

max_cache_age timedelta

Maximum age of cached API responses before refresh. Defaults to 1 hour.

max_count int

Maximum expected results per API request. Used to warn when response may have been trimmed. Defaults to 3500.

Attributes
headers property
headers: IdentityHeaders

HTTP headers for API requests.

url_api property
url_api: URL

RepeaterBook API base URL.

url_export_north_america property
url_export_north_america: URL

North-america export URL.

url_export_rest_of_world property
url_export_rest_of_world: URL

Rest of world (not north-america) export URL.

Functions
cache_dir async
cache_dir() -> Path

Cache directory for API responses.

Returns:

Type Description
Path

The cache directory, created if it did not already exist.

Raises:

Type Description
RepeaterBookCacheError

If the directory cannot be created, e.g. a read-only working directory.

Source code in src/repeaterbook/services.py
async def cache_dir(self) -> Path:
    """Cache directory for API responses.

    Returns:
        The cache directory, created if it did not already exist.

    Raises:
        RepeaterBookCacheError: If the directory cannot be created, e.g. a
            read-only working directory.
    """
    cache = self._cache_path
    if not await cache.exists():
        logger.info("Creating cache directory.")
        with _cache_errors("create", cache):
            await cache.mkdir(parents=True, exist_ok=True)
        gitignore = cache / ".gitignore"
        if not await gitignore.exists():
            logger.info("Creating .gitignore file.")
            # Best-effort: the .gitignore is a courtesy to keep the cache
            # out of a caller's repo, not something to fail a fetch over.
            with suppress(OSError):
                await gitignore.write_text("*\n", encoding="utf-8")
    return cache
clear_cache async
clear_cache() -> int

Delete every cached API response, forcing the next export to hit the network.

Only the entries fetch_json writes are removed. The directory itself, its .gitignore, and anything else a caller may have put there are left alone. A cache directory that does not exist yet is not created.

This is independent of the local database: RepeaterBook.truncate empties the store, and this empties the cache that would otherwise refill it with the same data. Clear both to guarantee a genuine re-download.

Returns:

Type Description
int

The number of cached responses removed.

Raises:

Type Description
RepeaterBookCacheError

If an entry cannot be removed, e.g. a read-only cache directory.

Source code in src/repeaterbook/services.py
async def clear_cache(self) -> int:
    """Delete every cached API response, forcing the next export to hit the network.

    Only the entries `fetch_json` writes are removed. The directory itself,
    its `.gitignore`, and anything else a caller may have put there are
    left alone. A cache directory that does not exist yet is not created.

    This is independent of the local database: `RepeaterBook.truncate` empties
    the store, and this empties the cache that would otherwise refill it
    with the same data. Clear both to guarantee a genuine re-download.

    Returns:
        The number of cached responses removed.

    Raises:
        RepeaterBookCacheError: If an entry cannot be removed, e.g. a
            read-only cache directory.
    """
    # Not `cache_dir()`: that creates the directory, and clearing a cache
    # that was never written should not leave one behind.
    removed = 0
    # Sweep stray `.tmp` files along with the committed `.json` entries. A
    # `.tmp` is only left behind by a hard crash mid-download and is never
    # read, but nothing else reclaims it. Only committed entries count as
    # responses, so a leftover temp does not inflate the number reported.
    async for entry in self._cache_path.glob(f"{CACHE_ENTRY_PREFIX}*"):
        with _cache_errors("remove", entry):
            await entry.unlink()
        if entry.suffix == ".json":
            removed += 1
    logger.info(f"Cleared {removed} cached API responses.")
    return removed
urls_export
urls_export(query: ExportQuery) -> set[URL]

Generate export URLs for given query.

Smart routing logic: - If NA-specific fields are used (state_id, county, emcomm, stype), only query the NA endpoint - If ROW-specific fields are used (region), only query the ROW endpoint - If countries are specified, route based on whether they're NA or ROW - If no routing hints, query both endpoints

Source code in src/repeaterbook/services.py
def urls_export(
    self,
    query: ExportQuery,
) -> set[URL]:
    """Generate export URLs for given query.

    Smart routing logic:
    - If NA-specific fields are used (state_id, county, emcomm, stype),
      only query the NA endpoint
    - If ROW-specific fields are used (region), only query the ROW endpoint
    - If countries are specified, route based on whether they're NA or ROW
    - If no routing hints, query both endpoints
    """
    mode_map: dict[Mode, ModeJSON] = {
        Mode.ANALOG: "analog",
        Mode.DMR: "DMR",
        Mode.NXDN: "NXDN",
        Mode.P25: "P25",
        Mode.TETRA: "tetra",
    }
    emergency_map: dict[Emergency, EmergencyJSON] = {
        Emergency.ARES: "ARES",
        Emergency.RACES: "RACES",
        Emergency.SKYWARN: "SKYWARN",
        Emergency.CANWARN: "CANWARN",
    }
    type_map: dict[ServiceType, ServiceTypeJSON] = {
        ServiceType.GMRS: "GMRS",
    }

    # Determine which endpoints to query based on the query parameters
    has_na_specific = bool(
        query.state_ids
        or query.counties
        or query.emergency_services
        or query.service_types
    )
    has_row_specific = bool(query.regions)

    # Check if countries are specified and categorize them
    query_countries = {country.name for country in query.countries}
    has_na_countries = bool(query_countries & self.NA_COUNTRIES)
    has_row_countries = bool(query_countries - self.NA_COUNTRIES)

    # Determine which endpoints to query
    query_na_endpoint = True
    query_row_endpoint = True

    if has_na_specific and not has_row_specific:
        # NA-specific fields used, only query NA
        query_row_endpoint = False
    elif has_row_specific and not has_na_specific:
        # ROW-specific fields used, only query ROW
        query_na_endpoint = False
    elif query_countries:
        # Countries specified - route based on country location
        query_na_endpoint = has_na_countries
        query_row_endpoint = has_row_countries

    query_na = ExportNorthAmericaQuery(
        callsign=list(query.callsigns),
        city=list(query.cities),
        landmark=list(query.landmarks),
        country=[country.name for country in query.countries],
        frequency=[str(frequency) for frequency in query.frequencies],
        mode=[mode_map[mode] for mode in query.modes],
        state_id=list(query.state_ids),
        county=list(query.counties),
        emcomm=[emergency_map[emergency] for emergency in query.emergency_services],
        stype=[type_map[service_type] for service_type in query.service_types],
    )
    # Safe cast: dict comprehension preserves TypedDict structure, only removes
    # empty values (which are optional in ExportNorthAmericaQuery).
    query_na = cast(
        "ExportNorthAmericaQuery", {k: v for k, v in query_na.items() if v}
    )

    query_world = ExportWorldQuery(
        callsign=list(query.callsigns),
        city=list(query.cities),
        landmark=list(query.landmarks),
        country=[country.name for country in query.countries],
        frequency=[str(frequency) for frequency in query.frequencies],
        mode=[mode_map[mode] for mode in query.modes],
        region=list(query.regions),
    )
    # Safe cast: dict comprehension preserves TypedDict structure, only removes
    # empty values (which are optional in ExportWorldQuery).
    query_world = cast(
        "ExportWorldQuery", {k: v for k, v in query_world.items() if v}
    )

    # Safe casts: URL % operator expects dict[str, str], and TypedDict values
    # are all list[str] which serialize correctly for query parameters.
    urls: set[URL] = set()
    if query_na_endpoint:
        na_params = cast("dict[str, str]", query_na)
        urls.add(self.url_export_north_america % na_params)
    if query_row_endpoint:
        row_params = cast("dict[str, str]", query_world)
        urls.add(self.url_export_rest_of_world % row_params)
    return urls
export_json async
export_json(url: URL) -> ExportJSON

Export data for given URL.

Source code in src/repeaterbook/services.py
async def export_json(self, url: URL) -> ExportJSON:
    """Export data for given URL."""
    data: Any = await fetch_json(
        url,
        headers=self.headers,
        cache_dir=await self.cache_dir(),
        max_cache_age=self.max_cache_age,
    )

    if not isinstance(data, dict):
        msg = f"Expected dict response from API, got {type(data).__name__}"
        raise RepeaterBookValidationError(msg)

    data = cast("dict[str, Any]", data)

    if (
        data.get("status") == "error"
        or data.get("ok") is False
        or data.get("error_code")
    ):
        message = data.get("message")
        error_code = data.get("error_code")
        raise RepeaterBookAPIError(
            message if isinstance(message, str) else "Unknown API error",
            status_code=HTTPStatus.OK,
            error_code=error_code if isinstance(error_code, str) else None,
            url=str(url),
            body=data,
        )

    if "count" not in data or "results" not in data:
        msg = "API response missing required 'count' or 'results' field"
        raise RepeaterBookValidationError(msg)

    export = cast("ExportJSON", data)

    if export["count"] >= self.max_count:
        logger.warning(
            "Reached max count for API response. Response may have been trimmed."
        )

    if export["count"] != len(export["results"]):
        logger.warning("Mismatched count and length of results.")

    return export
export_multi_json async
export_multi_json(urls: set[URL]) -> list[ExportJSON]

Export data for given URLs.

Source code in src/repeaterbook/services.py
async def export_multi_json(self, urls: set[URL]) -> list[ExportJSON]:
    """Export data for given URLs."""
    tasks = [self.export_json(url) for url in urls]
    return await asyncio.gather(*tasks)
download async
download(query: ExportQuery, *, strict: bool = False, skipped: list[RepeaterBookRowError] | None = None) -> list[Repeater]

Download repeaters.

Rows that cannot be modelled are logged and skipped, so a single malformed record does not discard an otherwise good response. The RepeaterBook data is community-maintained and such rows do occur.

Parameters:

Name Type Description Default
query ExportQuery

The export query to download.

required
strict bool

When True, raise RepeaterBookRowError on the first unmodellable row instead of skipping it.

False
skipped list[RepeaterBookRowError] | None

Optional list to collect a RepeaterBookRowError per skipped row.

None

Returns:

Type Description
list[Repeater]

The downloaded repeaters, minus any skipped rows.

Raises:

Type Description
RepeaterBookRowError

If strict is True and a row cannot be converted.

Source code in src/repeaterbook/services.py
async def download(
    self,
    query: ExportQuery,
    *,
    strict: bool = False,
    skipped: list[RepeaterBookRowError] | None = None,
) -> list[Repeater]:
    """Download repeaters.

    Rows that cannot be modelled are logged and skipped, so a single
    malformed record does not discard an otherwise good response. The
    RepeaterBook data is community-maintained and such rows do occur.

    Args:
        query: The export query to download.
        strict: When True, raise `RepeaterBookRowError` on the first
            unmodellable row instead of skipping it.
        skipped: Optional list to collect a `RepeaterBookRowError` per
            skipped row.

    Returns:
        The downloaded repeaters, minus any skipped rows.

    Raises:
        RepeaterBookRowError: If `strict` is True and a row cannot be
            converted.
    """
    data = await self.export_multi_json(self.urls_export(query))

    results: list[RepeaterJSON] = []
    for export in data:
        results.extend(export["results"])

    repeaters = json_to_models(results, strict=strict, skipped=skipped)

    logger.info(f"Downloaded {len(repeaters)} of {len(results)} repeaters.")
    return repeaters

Functions

fetch_json async

fetch_json(url: URL, *, headers: IdentityHeaders | None = None, cache_dir: Path | None = None, max_cache_age: timedelta = timedelta(seconds=3600), chunk_size: int = 1024) -> Any

Fetches JSON data from the specified URL using a streaming response.

  • If a cached copy exists and is recent (not older than max_cache_age seconds) and not forced, it loads and returns the cached data.
  • Otherwise, it streams the data in chunks while displaying a progress bar, caches it, and returns the parsed JSON data.

A cache entry that is missing or unparseable is treated as a miss and refetched. A failure to write the cache is an error, not a miss, and is raised as RepeaterBookCacheError -- returning data the caller believes was cached would silently refetch on every subsequent call.

Raises:

Type Description
RepeaterBookCacheError

If the cache entry cannot be written or read back.

Source code in src/repeaterbook/services.py
async def fetch_json(
    url: URL,
    *,
    headers: IdentityHeaders | None = None,
    cache_dir: Path | None = None,
    max_cache_age: timedelta = timedelta(seconds=3600),
    chunk_size: int = 1024,
) -> Any:  # noqa: ANN401 - json.loads() returns Any; validation done by callers
    """Fetches JSON data from the specified URL using a streaming response.

    - If a cached copy exists and is recent (not older than max_cache_age seconds) and
      not forced, it loads and returns the cached data.
    - Otherwise, it streams the data in chunks while displaying a progress bar, caches
      it, and returns the parsed JSON data.

    A cache entry that is missing or unparseable is treated as a miss and refetched.
    A failure to *write* the cache is an error, not a miss, and is raised as
    `RepeaterBookCacheError` -- returning data the caller believes was cached
    would silently refetch on every subsequent call.

    Raises:
        RepeaterBookCacheError: If the cache entry cannot be written or read back.
    """
    # Create a unique filename for caching based on the URL hash.
    if cache_dir is None:
        cache_dir = Path()
    hashed_url = hashlib.sha256(str(url).encode("utf-8")).hexdigest()
    cache_file = cache_dir / f"{CACHE_ENTRY_PREFIX}{hashed_url}.json"
    temp_file = cache_dir / f"{CACHE_ENTRY_PREFIX}{hashed_url}.tmp"

    # Check if fresh cached data exists using a single stat call.
    with suppress(FileNotFoundError, json.JSONDecodeError):
        stat = await cache_file.stat()
        file_age = time.time() - stat.st_mtime
        if file_age < max_cache_age.total_seconds():
            logger.info("Using cached data.")
            return json.loads(await cache_file.read_text(encoding="utf-8"))

    # Cache doesn't exist or is invalid, continue to fetch
    logger.info("Fetching new data from API...")
    try:
        await _download_to_cache(
            url,
            headers=headers,
            cache_file=cache_file,
            temp_file=temp_file,
            chunk_size=chunk_size,
        )
    except BaseException:
        # Never leave a partial .tmp behind. It is not named as a cache entry
        # so it would never be read, only accumulate. Cleanup failure is
        # suppressed so it cannot mask the error that got us here.
        with suppress(OSError):
            await temp_file.unlink(missing_ok=True)
        raise

    # After saving the file, load and parse the JSON data.
    with _cache_errors("read back", cache_file):
        return json.loads(await cache_file.read_text(encoding="utf-8"))

parse_date

parse_date(date_str: str) -> date

Parses a date string in the format YYYY-MM-DD.

Source code in src/repeaterbook/services.py
def parse_date(date_str: str) -> date:
    """Parses a date string in the format YYYY-MM-DD."""
    try:
        return date.fromisoformat(date_str)
    except ValueError:
        return date.min

json_to_model

json_to_model(j: RepeaterJSON) -> Repeater

Converts a JSON object to a Repeater model.

RepeaterBook export payloads vary slightly between endpoints.

  • exportROW.php may include extra keys like sponsor.
  • export.php (North America) includes keys like County/ARES/… and may omit Region.

This function should be resilient to those differences.

Source code in src/repeaterbook/services.py
def json_to_model(j: RepeaterJSON, /) -> Repeater:
    """Converts a JSON object to a Repeater model.

    RepeaterBook export payloads vary slightly between endpoints.

    - `exportROW.php` may include extra keys like `sponsor`.
    - `export.php` (North America) includes keys like `County`/`ARES`/… and may omit
      `Region`.

    This function should be resilient to those differences.
    """

    def s(key: str) -> str:
        """Safely parse RepeaterBook string fields."""
        v = j.get(key, "")
        return "" if v is None else str(v)

    def d(key: str) -> Decimal:
        """Safely parse RepeaterBook decimal fields."""
        v = j.get(key)
        if v is None:
            msg = f"Missing required decimal field: {key}"
            raise ValueError(msg)
        return Decimal(str(v))

    def b(key: str, *, default: bool = False) -> bool:
        """Parse RepeaterBook boolean-ish fields.

        RepeaterBook uses a mix of "Yes"/"No" strings and 1/0 ints.
        Missing/unknown values fall back to `default`. The decoding itself is
        `parse_flag`; this wrapper only adds the field name to the error.
        """
        try:
            return parse_flag(j.get(key), default=default)
        except TypeError as exc:
            msg = f"Invalid type for boolean field {key}: {type(j.get(key))}"
            raise TypeError(msg) from exc

    def parse_fm_bandwidth(value: str) -> Decimal | None:
        """Parse FM Bandwidth field, which may include " kHz" suffix."""
        return Decimal(value.replace(" kHz", "")) if value else None

    return Repeater.model_validate(
        Repeater(
            state_id=s("State ID"),
            repeater_id=int(j.get("Rptr ID", 0) or 0),
            frequency=d("Frequency"),
            input_frequency=d("Input Freq"),
            pl_ctcss_uplink=s("PL") or None,
            pl_ctcss_tsq_downlink=s("TSQ") or None,
            location_nearest_city=s("Nearest City"),
            landmark=s("Landmark") or None,
            region=j.get("Region"),
            country=s("Country") or None,
            county=s("County") or None,
            state=s("State") or None,
            latitude=d("Lat"),
            longitude=d("Long"),
            precise=b("Precise", default=False),
            callsign=s("Callsign") or None,
            use_membership=USE_MAP.get(s("Use"), Use.OPEN),
            operational_status=STATUS_MAP.get(s("Operational Status"), Status.UNKNOWN),
            # Tri-state, not `b()`: absent means unknown here, not False.
            ares=parse_yes_no(j.get("ARES")),
            races=parse_yes_no(j.get("RACES")),
            skywarn=parse_yes_no(j.get("SKYWARN")),
            canwarn=parse_yes_no(j.get("CANWARN")),
            allstar_node=s("AllStar Node") or None,
            echolink_node=s("EchoLink Node") or None,
            irlp_node=s("IRLP Node") or None,
            wires_node=s("Wires Node") or None,
            analog_capable=b("FM Analog", default=False),
            fm_bandwidth=parse_fm_bandwidth(s("FM Bandwidth")),
            dmr_capable=b("DMR", default=False),
            dmr_color_code=s("DMR Color Code") or None,
            dmr_id=s("DMR ID") or None,
            d_star_capable=b("D-Star", default=False),
            nxdn_capable=b("NXDN", default=False),
            apco_p_25_capable=b("APCO P-25", default=False),
            p_25_nac=s("P-25 NAC") or None,
            m17_capable=b("M17", default=False),
            m17_can=s("M17 CAN") or None,
            tetra_capable=b("Tetra", default=False),
            tetra_mcc=s("Tetra MCC") or None,
            tetra_mnc=s("Tetra MNC") or None,
            yaesu_system_fusion_capable=b("System Fusion", default=False),
            ysf_digital_id_downlink=None,
            ysf_digital_id_uplink=None,
            ysf_dsc=None,
            notes=s("Notes") or None,
            last_update=parse_date(s("Last Update")),
        )
    )

row_label

row_label(j: RepeaterJSON) -> str

Best-effort human identifier for an export row, for logs and errors.

Renders as "<State ID>:<Rptr ID> (<Callsign>)", omitting whatever the row does not carry, and falling back to "<unidentified>" for a row with none of the three.

Source code in src/repeaterbook/services.py
def row_label(j: RepeaterJSON, /) -> str:
    """Best-effort human identifier for an export row, for logs and errors.

    Renders as `"<State ID>:<Rptr ID> (<Callsign>)"`, omitting whatever the row
    does not carry, and falling back to `"<unidentified>"` for a row with none
    of the three.
    """
    state_id = j.get("State ID")
    repeater_id = j.get("Rptr ID")
    callsign = j.get("Callsign")

    parts = [str(part) for part in (state_id, repeater_id) if part not in (None, "")]
    ident = ":".join(parts)
    if callsign:
        ident = f"{ident} ({callsign})" if ident else f"({callsign})"
    return ident or "<unidentified>"

json_to_models

json_to_models(results: Iterable[RepeaterJSON], /, *, strict: bool = False, skipped: list[RepeaterBookRowError] | None = None) -> list[Repeater]

Convert export rows to Repeater models, tolerating unmodellable rows.

RepeaterBook's data is community-maintained, so a batch occasionally contains a row that cannot be modelled -- a zero input frequency, an out-of-range coordinate, a missing frequency. Converting the batch all-or-nothing means one such row discards every good record alongside it.

Parameters:

Name Type Description Default
results Iterable[RepeaterJSON]

Raw export rows.

required
strict bool

When True, re-raise the first unmodellable row as a RepeaterBookRowError instead of skipping it.

False
skipped list[RepeaterBookRowError] | None

Optional list to collect a RepeaterBookRowError per skipped row. Lets a caller inspect what was dropped without scraping logs.

None

Returns:

Type Description
list[Repeater]

The successfully converted repeaters, in input order.

Raises:

Type Description
RepeaterBookRowError

If strict is True and a row cannot be converted.

Source code in src/repeaterbook/services.py
def json_to_models(
    results: Iterable[RepeaterJSON],
    /,
    *,
    strict: bool = False,
    skipped: list[RepeaterBookRowError] | None = None,
) -> list[Repeater]:
    """Convert export rows to `Repeater` models, tolerating unmodellable rows.

    RepeaterBook's data is community-maintained, so a batch occasionally
    contains a row that cannot be modelled -- a zero input frequency, an
    out-of-range coordinate, a missing frequency. Converting the batch
    all-or-nothing means one such row discards every good record alongside it.

    Args:
        results: Raw export rows.
        strict: When True, re-raise the first unmodellable row as a
            `RepeaterBookRowError` instead of skipping it.
        skipped: Optional list to collect a `RepeaterBookRowError` per skipped
            row. Lets a caller inspect what was dropped without scraping logs.

    Returns:
        The successfully converted repeaters, in input order.

    Raises:
        RepeaterBookRowError: If `strict` is True and a row cannot be
            converted.
    """
    repeaters: list[Repeater] = []
    errors: list[RepeaterBookRowError] = []

    for result in results:
        try:
            repeaters.append(json_to_model(result))
        except ROW_ERRORS as exc:
            label = row_label(result)
            error = RepeaterBookRowError(str(exc), row=result, label=label)
            if strict:
                raise error from exc
            errors.append(error)
            logger.warning(f"Skipping unmodellable repeater {label}: {exc}")

    if errors:
        labels = ", ".join(str(error.label) for error in errors)
        logger.warning(
            f"Skipped {len(errors)} unmodellable of {len(errors) + len(repeaters)} "
            f"repeaters: {labels}"
        )
    if skipped is not None:
        skipped.extend(errors)

    return repeaters

Database

SQLite persistence.

repeaterbook.database

Internal database module for the RepeaterBook Python Client.

Classes

RepeaterBook

Local database for repeater data from the RepeaterBook.com API.

This file is a cache, not durable storage. It holds nothing that cannot be re-downloaded from RepeaterBook, so when the schema in code no longer matches the schema the file was written with, the file is discarded and rebuilt rather than migrated. Keep your own data somewhere else.

The underlying engine and its connection pool are created lazily on first use and live until close() is called, so use the instance as a context manager (or call close() yourself) to release the SQLite handle when you are done. Closing is optional: an instance that is never closed still works, and its connections are finalized when it is garbage collected.

Attributes
database_path property
database_path: Path

Database path.

database_uri property
database_uri: str

Database URI.

engine cached property
engine: Engine

Create database engine, discarding the file if its schema is stale.

The check lives here rather than in init_db because reading from a stale file has to be caught too, and query never calls init_db. This is the one path every caller goes through.

Functions
close
close() -> None

Dispose of the engine and release its pooled SQLite connections.

The instance stays usable: the next access to engine (directly or via populate, query or truncate) builds a fresh one, re-running the staleness check. Calling this on an instance whose engine was never built, or that is already closed, is a no-op.

Any Session you built against the old engine yourself is not tracked here; close those first.

Source code in src/repeaterbook/database.py
def close(self) -> None:
    """Dispose of the engine and release its pooled SQLite connections.

    The instance stays usable: the next access to `engine` (directly or
    via `populate`, `query` or `truncate`) builds a fresh one, re-running
    the staleness check. Calling this on an instance whose engine was
    never built, or that is already closed, is a no-op.

    Any `Session` you built against the old `engine` yourself is not
    tracked here; close those first.
    """
    # `attrs.frozen` makes the class slotted, so the cached engine lives in
    # a slot rather than `__dict__`, and `del self.engine` is refused by
    # the frozen `__delattr__`. Going through `object` bypasses both the
    # freeze and attrs' lazy-building `__getattr__`: an empty slot raises
    # rather than constructing an engine only to throw it away.
    try:
        engine: Engine = object.__getattribute__(self, "engine")
    except AttributeError:
        return
    object.__delattr__(self, "engine")
    engine.dispose()
    logger.debug(f"Closed database at {self.database_path}.")
init_db
init_db() -> None

Initialize database, recording the schema it was created with.

Kept as public API, but building the engine already does this, so it is a no-op on an engine that has been touched.

Source code in src/repeaterbook/database.py
def init_db(self) -> None:
    """Initialize database, recording the schema it was created with.

    Kept as public API, but building the engine already does this, so it
    is a no-op on an engine that has been touched.
    """
    SQLModel.metadata.create_all(self.engine)
    self._record_fingerprint(self.engine)
populate
populate(repeaters: Iterable[Repeater]) -> None

Populate internal database.

Source code in src/repeaterbook/database.py
def populate(self, repeaters: Iterable[Repeater]) -> None:
    """Populate internal database."""
    self.init_db()

    with Session(self.engine) as session:
        for repeater in repeaters:
            session.merge(repeater)
        session.commit()

    logger.info("Populated repeaters.")
query
query(*where: _ColumnExpressionArgument[bool] | bool) -> Sequence[Repeater]

Query the database.

Source code in src/repeaterbook/database.py
def query(
    self,
    *where: _ColumnExpressionArgument[bool] | bool,
) -> Sequence[Repeater]:
    """Query the database."""
    with Session(self.engine) as session:
        statement = select(Repeater).where(*where)
        repeaters = session.exec(statement).all()

    logger.info(f"Found {len(repeaters)} repeaters.")

    return repeaters
truncate
truncate() -> int

Delete every repeater, leaving the file and its schema marker in place.

This empties the data without making the file look stale: the next open finds a current, empty database rather than one to discard. It does not touch the API response cache, which RepeaterBookAPI owns; a populate shortly after a truncate may therefore be served from that cache rather than the network.

Returns:

Type Description
int

The number of repeaters removed.

Source code in src/repeaterbook/database.py
def truncate(self) -> int:
    """Delete every repeater, leaving the file and its schema marker in place.

    This empties the data without making the file look stale: the next open
    finds a current, empty database rather than one to discard. It does
    not touch the API response cache, which `RepeaterBookAPI` owns; a
    `populate` shortly after a truncate may therefore be served from that
    cache rather than the network.

    Returns:
        The number of repeaters removed.
    """
    with Session(self.engine) as session:
        removed = session.exec(delete(Repeater)).rowcount
        session.commit()

    logger.info(f"Truncated {removed} repeaters.")
    return removed

Functions

schema_fingerprint

schema_fingerprint() -> str

Return a digest of the ORM schema as currently defined in code.

Derived from the model metadata rather than hand-maintained, so it moves on its own whenever a column is added, removed, renamed, retyped, or has its nullability or primary-key membership changed. A contributor changing the model gets the stale-database wipe for free, without having to know this mechanism exists -- which is the point, because the failure mode of a forgotten manual bump is a silent misread rather than a loud error.

Deliberately over-sensitive: an index-only change also moves the digest, costing a re-download that was not strictly required. That is the right trade when the alternative is serving wrong data from a stale file.

Source code in src/repeaterbook/database.py
def schema_fingerprint() -> str:
    """Return a digest of the ORM schema as currently defined in code.

    Derived from the model metadata rather than hand-maintained, so it moves
    on its own whenever a column is added, removed, renamed, retyped, or has
    its nullability or primary-key membership changed. A contributor changing
    the model gets the stale-database wipe for free, without having to know
    this mechanism exists -- which is the point, because the failure mode of a
    forgotten manual bump is a silent misread rather than a loud error.

    Deliberately over-sensitive: an index-only change also moves the digest,
    costing a re-download that was not strictly required. That is the right
    trade when the alternative is serving wrong data from a stale file.
    """
    parts: list[str] = []
    for table in SQLModel.metadata.sorted_tables:
        parts.append(table.name)
        parts.extend(
            f"{column.name}:{column.type!r}:{column.nullable}:{column.primary_key}"
            for column in table.columns
        )
        parts.extend(sorted(index.name or "" for index in table.indexes))
    digest = hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest()
    return digest[:16]

Queries

Composable filter builders and the radius search.

repeaterbook.queries

Queries.

Classes

Band

Bases: NamedTuple

Band.

Bands

Bases: Band, Enum

Bands.

BandName

Bases: StrEnum

Amateur band names, as a string vocabulary.

Bands members carry their bounds as a NamedTuple value, which renders in JSON Schema as a two-number array -- meaningless to a consumer that just wants to name a band. This mirrors Bands member-for-member as plain strings; test_band_name_matches_bands guards against drift.

Functions

square

square(radius: Radius) -> ColumnElement[bool]

Return a query for repeaters within a given square.

Note: This is a square, not a circle. Use filter_radius afterwards.

Source code in src/repeaterbook/queries.py
def square(radius: Radius) -> ColumnElement[bool]:
    """Return a query for repeaters within a given square.

    Note: This is a square, not a circle. Use `filter_radius` afterwards.
    """
    bounds = square_bounds(radius=radius)
    return and_(
        Repeater.latitude >= bounds.south,
        Repeater.latitude <= bounds.north,
        Repeater.longitude >= bounds.west,
        Repeater.longitude <= bounds.east,
    )

filter_radius

filter_radius(repeaters: Iterable[Repeater], radius: Radius) -> list[Repeater]

Filter repeaters within a given radius, and sort by distance.

Use after square to limit the number of repeaters to check. This is a brute-force search, so it should be used with care.

Source code in src/repeaterbook/queries.py
def filter_radius(
    repeaters: Iterable[Repeater],
    radius: Radius,
) -> list[Repeater]:
    """Filter repeaters within a given radius, and sort by distance.

    Use after `square` to limit the number of repeaters to check.
    This is a brute-force search, so it should be used with care.
    """

    class RepDist(NamedTuple):
        """Repeater distance."""

        repeater: Repeater
        distance: float

    rep_dists: list[RepDist] = []
    for repeater in repeaters:
        # Calculate the distance to the repeater.
        distance = haversine(
            radius.origin,
            (repeater.latitude, repeater.longitude),
            unit=radius.unit,
        )

        if distance <= radius.distance:
            rep_dists.append(RepDist(repeater=repeater, distance=distance))

    # Sort by distance.
    rep_dists.sort(key=lambda x: x.distance)

    # Log the number of repeaters found.
    logger.info(
        f"Found {len(rep_dists)} repeaters within {radius.distance} {radius.unit.name}."
    )

    # Convert to a list of repeaters.
    return [rep_dist.repeater for rep_dist in rep_dists]

band_of

band_of(name: BandName) -> Bands

Return the Bands member, with its bounds, for a band name.

Source code in src/repeaterbook/queries.py
def band_of(name: BandName) -> Bands:
    """Return the `Bands` member, with its bounds, for a band name."""
    return Bands[name.value]

band

band(*bands: Band) -> ColumnElement[bool]

Return a query for repeaters within a given band.

Source code in src/repeaterbook/queries.py
def band(*bands: Band) -> ColumnElement[bool]:
    """Return a query for repeaters within a given band."""
    return or_(
        *(
            (Repeater.frequency >= band.low) & (Repeater.frequency <= band.high)
            for band in bands
        )
    )

Spec

RepeaterSpec, the neutral output contract, and its JSON Schema.

repeaterbook.spec

Neutral, source-agnostic repeater-spec contract and its mapper.

One RepeaterSpec is one programmable radio channel. A multi-mode repeater expands to one spec per mode. params is a union discriminated on its own mode field, and extra="forbid" on each params model is what makes a mode/params mismatch illegal by construction. RepeaterSpec.mode re-exposes params.mode at the top level, so the two can never disagree.

Internet-linking node ids (AllStar, EchoLink, IRLP, Wires-X) sit at the top level rather than in params: they are not RF modes and do not change how a channel is programmed, so they belong outside the mode-discriminated union.

Classes

RepeaterMode

Bases: StrEnum

A single radio operating mode for one programmable channel.

RepeaterStatus

Bases: StrEnum

Whether a repeater is currently on the air.

Mirrors repeaterbook.models.Status, but as a StrEnum so the member name is the wire value. Status uses auto(), whose integer values would otherwise leak into the published contract.

RepeaterUse

Bases: StrEnum

Who may use a repeater.

Mirrors repeaterbook.models.Use; see RepeaterStatus for why this is a separate StrEnum rather than a reuse of the core enum.

DStarParams

Bases: _Params

RepeaterBook carries no D-STAR parameters; intentionally empty.

NxdnParams

Bases: _Params

RepeaterBook carries no NXDN parameters; intentionally empty.

RepeaterSpec

Bases: BaseModel

One programmable radio channel; params is discriminated on its mode.

Attributes
mode property
mode: RepeaterMode

The channel's mode, derived from params so the two cannot disagree.

Tone

Bases: NamedTuple

A squelch tone for one signal direction: at most one of CTCSS or DCS.

Functions

repeater_spec_json_schema

repeater_spec_json_schema() -> dict[str, object]

Return the JSON Schema for RepeaterSpec, as it appears on the wire.

Generated in serialization mode on purpose: mode is a computed field, and Pydantic emits computed fields only into the serialization schema. The default validation mode would publish a contract missing the top-level mode key that this model actually serializes.

Source code in src/repeaterbook/spec.py
def repeater_spec_json_schema() -> dict[str, object]:
    """Return the JSON Schema for RepeaterSpec, as it appears on the wire.

    Generated in serialization mode on purpose: `mode` is a computed field, and
    Pydantic emits computed fields only into the serialization schema. The
    default validation mode would publish a contract missing the top-level
    `mode` key that this model actually serializes.
    """
    return _ADAPTER.json_schema(mode="serialization")

schema_path

schema_path() -> Path

Return the path to the published repeater-spec JSON Schema.

Source code in src/repeaterbook/spec.py
def schema_path() -> Path:
    """Return the path to the published repeater-spec JSON Schema."""
    return Path(__file__).parent / "schemas" / "repeater_spec.schema.json"

write_schema

write_schema() -> None

Regenerate the published JSON Schema from the model.

Source code in src/repeaterbook/spec.py
def write_schema() -> None:
    """Regenerate the published JSON Schema from the model."""
    path = schema_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(
        json.dumps(repeater_spec_json_schema(), indent=2) + "\n",
        encoding="utf-8",
    )

parse_tone

parse_tone(raw: str | None) -> Tone

Split a RepeaterBook tone string into its CTCSS and DCS parts.

RepeaterBook mixes CTCSS frequencies and DCS codes in one string field. Rule: "." -> CTCSS Decimal; "D"/"d" prefix -> DCS (letter stripped+uppercased); all-digits -> DCS; else an empty Tone.

Source code in src/repeaterbook/spec.py
def parse_tone(raw: str | None) -> Tone:
    """Split a RepeaterBook tone string into its CTCSS and DCS parts.

    RepeaterBook mixes CTCSS frequencies and DCS codes in one string field.
    Rule: "." -> CTCSS Decimal; "D"/"d" prefix -> DCS (letter stripped+uppercased);
    all-digits -> DCS; else an empty Tone.
    """
    if raw is None or not (value := raw.strip()):
        return Tone(None, None)
    if "." in value:
        try:
            return Tone(Decimal(value), None)
        except InvalidOperation:
            return Tone(None, None)
    if value[0] in {"D", "d"}:
        return Tone(None, value[1:].upper())
    if value.isdigit():
        return Tone(None, value)
    return Tone(None, None)

parse_node_id

parse_node_id(raw: str | None) -> str | None

Normalize a linking-node id, mapping RepeaterBook's absent-node forms to None.

RepeaterBook spells "this repeater has no node on this network" three ways: a missing key, an empty string, and the literal "0". Ingest already folds the first two to None (services.py uses or None), but "0" survives into the stored Repeater and is by far the most common value in real exports. Zero is not a valid id on AllStar, EchoLink, IRLP or Wires-X, so passing it through would make a non-null node field stop implying a dialable node and push the sentinel onto every consumer.

Source code in src/repeaterbook/spec.py
def parse_node_id(raw: str | None) -> str | None:
    """Normalize a linking-node id, mapping RepeaterBook's absent-node forms to None.

    RepeaterBook spells "this repeater has no node on this network" three ways:
    a missing key, an empty string, and the literal `"0"`. Ingest already folds
    the first two to None (`services.py` uses `or None`), but `"0"` survives into
    the stored `Repeater` and is by far the most common value in real exports.
    Zero is not a valid id on AllStar, EchoLink, IRLP or Wires-X, so passing it
    through would make a non-null node field stop implying a dialable node and
    push the sentinel onto every consumer.
    """
    if raw is None or not (value := raw.strip()):
        return None
    # Any all-zero spelling ("0", "00", ...) is the absent-node sentinel.
    return None if set(value) == {"0"} else value

freq_to_band

freq_to_band(freq: FrequencyMHz) -> str | None

Return the amateur band name for a frequency, or None if unknown.

Source code in src/repeaterbook/spec.py
def freq_to_band(freq: FrequencyMHz) -> str | None:
    """Return the amateur band name for a frequency, or None if unknown."""
    # Lazy import: breaks a models<->spec import cycle.
    from repeaterbook.queries import Bands  # noqa: PLC0415

    for b in Bands:
        if b.low <= freq <= b.high:
            return b.name
    return None

repeater_to_specs

repeater_to_specs(rep: Repeater, distance_km: Decimal | None = None) -> list[RepeaterSpec]

Expand one repeater into one spec per supported mode.

Source code in src/repeaterbook/spec.py
def repeater_to_specs(
    rep: Repeater,
    distance_km: Decimal | None = None,
) -> list[RepeaterSpec]:
    """Expand one repeater into one spec per supported mode."""
    uplink = parse_tone(rep.pl_ctcss_uplink)
    downlink = parse_tone(rep.pl_ctcss_tsq_downlink)
    modes = rep.modes or frozenset({RepeaterMode.FM})
    return [
        RepeaterSpec(
            name=rep.callsign or rep.location_nearest_city,
            callsign=rep.callsign,
            nearest_city=rep.location_nearest_city,
            rx_frequency_mhz=rep.frequency,
            tx_frequency_mhz=rep.input_frequency,
            ctcss_tx_hz=uplink.ctcss,
            ctcss_rx_hz=downlink.ctcss,
            dcs_tx_code=uplink.dcs,
            dcs_rx_code=downlink.dcs,
            latitude=rep.latitude,
            longitude=rep.longitude,
            distance_km=distance_km,
            operational_status=RepeaterStatus[rep.operational_status.name],
            use=RepeaterUse[rep.use_membership.name],
            band=freq_to_band(rep.frequency),
            notes=rep.notes,
            # Linking backends are mode-agnostic, so a multi-mode repeater
            # repeats them on every spec it fans out to.
            allstar_node=parse_node_id(rep.allstar_node),
            echolink_node=parse_node_id(rep.echolink_node),
            irlp_node=parse_node_id(rep.irlp_node),
            wires_node=parse_node_id(rep.wires_node),
            last_update=datetime.combine(
                rep.last_update, datetime.min.time(), tzinfo=UTC
            ),
            source_id=f"{rep.state_id}:{rep.repeater_id}",
            params=_ACCESSOR[mode](rep) or _DEFAULT_PARAMS[mode](),
        )
        for mode in modes
    ]

Utils

Geographic types and the constrained numeric aliases used across the contract.

repeaterbook.utils

Utilities.

Classes

LatLon

Bases: NamedTuple

Latitude and Longitude.

Radius

Bases: NamedTuple

Radius.

SquareBounds

Bases: NamedTuple

Square bounds.

Functions

square_bounds

square_bounds(radius: Radius) -> SquareBounds

Get the lat/lon box that contains every point within radius.

This is the coarse pre-filter behind queries.square, so it must never exclude a point that is actually in range; filter_radius does the exact check afterwards. Over-approximating is harmless, under-approximating silently drops repeaters. The bounds are therefore the true extremes of the circle, not merely the points due north/south/east/west of the origin, and are padded by a hair against rounding:

  • Latitude spans lat ± r (r in degrees of arc) and is clamped to the poles. A circle that reaches a pole wraps around it and covers every longitude, so the box is opened east-west.
  • Longitude is widest where a meridian is tangent to the circle, which lies poleward of the origin, not due east/west of it. Spherical trigonometry gives that half-width as asin(sin r / cos lat).
  • A circle that straddles the antimeridian would need two boxes. Repeater.longitude is stored in [-180, 180], so a bound pushed past either edge would exclude the far side; the box is opened east-west instead, and the exact pass tightens it.
  • Past half the circumference the whole globe is in range.
Source code in src/repeaterbook/utils.py
def square_bounds(radius: Radius) -> SquareBounds:
    """Get the lat/lon box that contains every point within `radius`.

    This is the coarse pre-filter behind `queries.square`, so it must never
    exclude a point that is actually in range; `filter_radius` does the exact
    check afterwards. Over-approximating is harmless, under-approximating
    silently drops repeaters. The bounds are therefore the true extremes of the
    circle, not merely the points due north/south/east/west of the origin, and
    are padded by a hair against rounding:

    * Latitude spans `lat ± r` (`r` in degrees of arc) and is clamped to the
      poles. A circle that reaches a pole wraps around it and covers every
      longitude, so the box is opened east-west.
    * Longitude is widest where a meridian is tangent to the circle, which
      lies poleward of the origin, not due east/west of it. Spherical
      trigonometry gives that half-width as `asin(sin r / cos lat)`.
    * A circle that straddles the antimeridian would need two boxes.
      `Repeater.longitude` is stored in `[-180, 180]`, so a bound pushed past
      either edge would exclude the far side; the box is opened east-west
      instead, and the exact pass tightens it.
    * Past half the circumference the whole globe is in range.
    """
    lat, lon = radius.origin
    arc = _angular_radius(radius)
    if arc >= math.pi:
        return SquareBounds(north=90.0, south=-90.0, east=180.0, west=-180.0)

    delta = math.degrees(arc) + _PADDING_DEG
    north = lat + delta
    south = lat - delta
    if north >= 90.0 or south <= -90.0:  # noqa: PLR2004 - the poles
        return SquareBounds(
            north=min(north, 90.0), south=max(south, -90.0), east=180.0, west=-180.0
        )

    # Neither pole is reached, so the circle lies strictly between them and
    # `cos(lat) > sin(arc)` holds: the ratio is inside `asin`'s domain. `min`
    # only absorbs rounding when both sides are within an ulp of 1.
    ratio = min(1.0, math.sin(arc) / math.cos(math.radians(lat)))
    half_width = math.degrees(math.asin(ratio)) + _PADDING_DEG
    east = lon + half_width
    west = lon - half_width
    if east > 180.0 or west < -180.0:  # noqa: PLR2004 - the antimeridian
        east = 180.0
        west = -180.0

    return SquareBounds(north=north, south=south, east=east, west=west)

Exceptions

repeaterbook.exceptions

Custom exceptions for the RepeaterBook Python Client.

Classes

RepeaterBookError

Bases: Exception

Base exception for the RepeaterBook Python Client.

All RepeaterBook Python Client exceptions inherit from this class, making it easy to catch all library errors with a single except clause.

RepeaterBookAPIError

RepeaterBookAPIError(message: str, *, status_code: int | None = None, error_code: str | None = None, url: str | None = None, body: object | None = None)

Bases: RepeaterBookError

Error returned by the RepeaterBook API.

Raised when the API returns an error response (status: "error"). The error message from the API is preserved in the exception message.

Initialize an API error with optional structured response context.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    error_code: str | None = None,
    url: str | None = None,
    body: object | None = None,
) -> None:
    """Initialize an API error with optional structured response context."""
    self.message = message
    self.status_code = status_code
    self.error_code = error_code
    self.url = url
    self.body = body
    super().__init__(message)

RepeaterBookUnauthorizedError

RepeaterBookUnauthorizedError(message: str, *, status_code: int | None = None, error_code: str | None = None, url: str | None = None, body: object | None = None)

Bases: RepeaterBookAPIError

Unauthorized access to the API.

Raised when the API returns a 401 Unauthorized status code, indicating that authentication is required or has failed.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    error_code: str | None = None,
    url: str | None = None,
    body: object | None = None,
) -> None:
    """Initialize an API error with optional structured response context."""
    self.message = message
    self.status_code = status_code
    self.error_code = error_code
    self.url = url
    self.body = body
    super().__init__(message)

RepeaterBookForbiddenError

RepeaterBookForbiddenError(message: str, *, status_code: int | None = None, error_code: str | None = None, url: str | None = None, body: object | None = None)

Bases: RepeaterBookAPIError

Authenticated but not authorized to access the API.

Raised when the API returns a 403 Forbidden status code, such as when User-Agent policy enforcement or an authorization scope denies access.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    status_code: int | None = None,
    error_code: str | None = None,
    url: str | None = None,
    body: object | None = None,
) -> None:
    """Initialize an API error with optional structured response context."""
    self.message = message
    self.status_code = status_code
    self.error_code = error_code
    self.url = url
    self.body = body
    super().__init__(message)

RepeaterBookRateLimitError

RepeaterBookRateLimitError(message: str, *, retry_after: float | None = None, **kwargs: Unpack[_APIErrorContext])

Bases: RepeaterBookAPIError

API request rejected because the rate limit was exceeded.

Raised when the API returns a 429 Too Many Requests status code.

Initialize a rate-limit error with an optional retry delay.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    retry_after: float | None = None,
    **kwargs: Unpack[_APIErrorContext],
) -> None:
    """Initialize a rate-limit error with an optional retry delay."""
    super().__init__(message, **kwargs)
    self.retry_after = retry_after

RepeaterBookCacheError

Bases: RepeaterBookError

Error during cache operations.

Raised when reading from or writing to the cache fails, such as file permission issues or disk full errors.

RepeaterBookValidationError

Bases: RepeaterBookError

Invalid data or response format.

Raised when: - API response is not in expected format (not a dict) - Required fields are missing from the response - Data values fail validation (e.g., invalid coordinates)

RepeaterBookRowError

RepeaterBookRowError(message: str, *, row: object | None = None, label: str | None = None)

Bases: RepeaterBookValidationError

A single export row could not be converted into a Repeater.

RepeaterBook data is community-maintained, so individual rows are occasionally unmodellable (a zero input frequency, an out-of-range coordinate, a missing frequency). This wraps the underlying parse or validation failure together with the offending row, so a caller can tell which record failed and why.

By default RepeaterBookAPI.download logs and skips these rather than raising, so one bad row cannot discard an otherwise good response. Pass strict=True to have them propagate instead.

Attributes:

Name Type Description
row

The raw export row that failed to convert.

label

Best-effort identifier for the row, e.g. "48:24371 (W5AW)".

Initialize a row error with the offending row and its label.

Source code in src/repeaterbook/exceptions.py
def __init__(
    self,
    message: str,
    *,
    row: object | None = None,
    label: str | None = None,
) -> None:
    """Initialize a row error with the offending row and its label."""
    self.message = message
    self.row = row
    self.label = label
    super().__init__(message)

North American state IDs

RepeaterBook's own state_id vocabulary for the US, Canada and Mexico.

repeaterbook.na_states

RepeaterBook's own North American state and province identifiers.

RepeaterBook scopes North American queries with a state_id whose values are its own invention. They are not ISO 3166-2, and cannot be derived from it, so a general-purpose library such as pycountry is no help here:

=============== ============== ============== Subdivision RepeaterBook ISO 3166-2 =============== ============== ============== California 06 US-CA Alberta CA01 CA-AB Jalisco MX14 MX-JAL =============== ============== ==============

The United States uses two-digit FIPS codes, which RepeaterBook's API documentation calls out as "State ID (FIPS)". Canada and Mexico use bespoke CA##/MX## numbering that RepeaterBook does not document at all -- hence this module. Canada numbers its provinces alphabetically and appends the three territories; Mexico follows the INEGI alphabetical ordering.

Knowing these up front matters because the API truncates a response at 3500 results. Querying a whole country silently returns a partial answer, and any subdivision missing from that slice is invisible -- so the identifiers cannot be discovered by downloading first and reading them back off the data.

The values are also unforgiving: "6" is not "06" and returns an empty result rather than an error, and lower-case ca01 is rejected outright. Selecting a member avoids inventing either mistake.

Classes

NAState

Bases: StrEnum

A North American state_id accepted by RepeaterBook's export API.

Members are named <country>_<subdivision> using each country's usual abbreviations, and each value is the identifier RepeaterBook expects.

Attributes
US_AL class-attribute instance-attribute
US_AL = '01'

Alabama.

US_AK class-attribute instance-attribute
US_AK = '02'

Alaska.

US_AZ class-attribute instance-attribute
US_AZ = '04'

Arizona.

US_AR class-attribute instance-attribute
US_AR = '05'

Arkansas.

US_CA class-attribute instance-attribute
US_CA = '06'

California.

US_CO class-attribute instance-attribute
US_CO = '08'

Colorado.

US_CT class-attribute instance-attribute
US_CT = '09'

Connecticut.

US_DE class-attribute instance-attribute
US_DE = '10'

Delaware.

US_DC class-attribute instance-attribute
US_DC = '11'

District of Columbia.

US_FL class-attribute instance-attribute
US_FL = '12'

Florida.

US_GA class-attribute instance-attribute
US_GA = '13'

Georgia.

US_HI class-attribute instance-attribute
US_HI = '15'

Hawaii.

US_ID class-attribute instance-attribute
US_ID = '16'

Idaho.

US_IL class-attribute instance-attribute
US_IL = '17'

Illinois.

US_IN class-attribute instance-attribute
US_IN = '18'

Indiana.

US_IA class-attribute instance-attribute
US_IA = '19'

Iowa.

US_KS class-attribute instance-attribute
US_KS = '20'

Kansas.

US_KY class-attribute instance-attribute
US_KY = '21'

Kentucky.

US_LA class-attribute instance-attribute
US_LA = '22'

Louisiana.

US_ME class-attribute instance-attribute
US_ME = '23'

Maine.

US_MD class-attribute instance-attribute
US_MD = '24'

Maryland.

US_MA class-attribute instance-attribute
US_MA = '25'

Massachusetts.

US_MI class-attribute instance-attribute
US_MI = '26'

Michigan.

US_MN class-attribute instance-attribute
US_MN = '27'

Minnesota.

US_MS class-attribute instance-attribute
US_MS = '28'

Mississippi.

US_MO class-attribute instance-attribute
US_MO = '29'

Missouri.

US_MT class-attribute instance-attribute
US_MT = '30'

Montana.

US_NE class-attribute instance-attribute
US_NE = '31'

Nebraska.

US_NV class-attribute instance-attribute
US_NV = '32'

Nevada.

US_NH class-attribute instance-attribute
US_NH = '33'

New Hampshire.

US_NJ class-attribute instance-attribute
US_NJ = '34'

New Jersey.

US_NM class-attribute instance-attribute
US_NM = '35'

New Mexico.

US_NY class-attribute instance-attribute
US_NY = '36'

New York.

US_NC class-attribute instance-attribute
US_NC = '37'

North Carolina.

US_ND class-attribute instance-attribute
US_ND = '38'

North Dakota.

US_OH class-attribute instance-attribute
US_OH = '39'

Ohio.

US_OK class-attribute instance-attribute
US_OK = '40'

Oklahoma.

US_OR class-attribute instance-attribute
US_OR = '41'

Oregon.

US_PA class-attribute instance-attribute
US_PA = '42'

Pennsylvania.

US_RI class-attribute instance-attribute
US_RI = '44'

Rhode Island.

US_SC class-attribute instance-attribute
US_SC = '45'

South Carolina.

US_SD class-attribute instance-attribute
US_SD = '46'

South Dakota.

US_TN class-attribute instance-attribute
US_TN = '47'

Tennessee.

US_TX class-attribute instance-attribute
US_TX = '48'

Texas.

US_UT class-attribute instance-attribute
US_UT = '49'

Utah.

US_VT class-attribute instance-attribute
US_VT = '50'

Vermont.

US_VA class-attribute instance-attribute
US_VA = '51'

Virginia.

US_WA class-attribute instance-attribute
US_WA = '53'

Washington.

US_WV class-attribute instance-attribute
US_WV = '54'

West Virginia.

US_WI class-attribute instance-attribute
US_WI = '55'

Wisconsin.

US_WY class-attribute instance-attribute
US_WY = '56'

Wyoming.

US_AS class-attribute instance-attribute
US_AS = '60'

American Samoa.

US_GU class-attribute instance-attribute
US_GU = '66'

Guam.

US_MP class-attribute instance-attribute
US_MP = '69'

Northern Mariana Islands.

US_PR class-attribute instance-attribute
US_PR = '72'

Puerto Rico.

US_VI class-attribute instance-attribute
US_VI = '78'

Virgin Islands.

CA_AB class-attribute instance-attribute
CA_AB = 'CA01'

Alberta.

CA_BC class-attribute instance-attribute
CA_BC = 'CA02'

British Columbia.

CA_MB class-attribute instance-attribute
CA_MB = 'CA03'

Manitoba.

CA_NB class-attribute instance-attribute
CA_NB = 'CA04'

New Brunswick.

CA_NL class-attribute instance-attribute
CA_NL = 'CA05'

Newfoundland. RepeaterBook omits "and Labrador".

CA_NS class-attribute instance-attribute
CA_NS = 'CA07'

Nova Scotia.

CA_ON class-attribute instance-attribute
CA_ON = 'CA08'

Ontario.

CA_PE class-attribute instance-attribute
CA_PE = 'CA09'

Prince Edward Island.

CA_QC class-attribute instance-attribute
CA_QC = 'CA10'

Quebec.

CA_SK class-attribute instance-attribute
CA_SK = 'CA11'

Saskatchewan.

CA_YT class-attribute instance-attribute
CA_YT = 'CA12'

Yukon Territory. RepeaterBook retains the pre-2003 name.

CA_NT class-attribute instance-attribute
CA_NT = 'CA13'

Northwest Territories.

CA_NU class-attribute instance-attribute
CA_NU = 'CA14'

Nunavut.

MX_AGU class-attribute instance-attribute
MX_AGU = 'MX01'

Aguascalientes.

MX_BCN class-attribute instance-attribute
MX_BCN = 'MX02'

Baja California.

MX_BCS class-attribute instance-attribute
MX_BCS = 'MX03'

Baja California Sur.

MX_CAM class-attribute instance-attribute
MX_CAM = 'MX04'

Campeche.

MX_CHP class-attribute instance-attribute
MX_CHP = 'MX05'

Chiapas.

MX_CHH class-attribute instance-attribute
MX_CHH = 'MX06'

Chihuahua.

MX_COA class-attribute instance-attribute
MX_COA = 'MX07'

Coahuila.

MX_COL class-attribute instance-attribute
MX_COL = 'MX08'

Colima.

MX_CMX class-attribute instance-attribute
MX_CMX = 'MX09'

Mexico City. INEGI lists this as Distrito Federal.

MX_DUR class-attribute instance-attribute
MX_DUR = 'MX10'

Durango.

MX_GUA class-attribute instance-attribute
MX_GUA = 'MX11'

Guanajuato.

MX_GRO class-attribute instance-attribute
MX_GRO = 'MX12'

Guerrero.

MX_HID class-attribute instance-attribute
MX_HID = 'MX13'

Hidalgo.

MX_JAL class-attribute instance-attribute
MX_JAL = 'MX14'

Jalisco.

MX_MEX class-attribute instance-attribute
MX_MEX = 'MX15'

Mexico, the state.

MX_MIC class-attribute instance-attribute
MX_MIC = 'MX16'

Michoacan.

MX_MOR class-attribute instance-attribute
MX_MOR = 'MX17'

Morelos.

MX_NAY class-attribute instance-attribute
MX_NAY = 'MX18'

Nayarit.

MX_NLE class-attribute instance-attribute
MX_NLE = 'MX19'

Nuevo Leon.

MX_OAX class-attribute instance-attribute
MX_OAX = 'MX20'

Oaxaca.

MX_PUE class-attribute instance-attribute
MX_PUE = 'MX21'

Puebla.

MX_QUE class-attribute instance-attribute
MX_QUE = 'MX22'

Queretaro.

MX_ROO class-attribute instance-attribute
MX_ROO = 'MX23'

Quintana Roo.

MX_SLP class-attribute instance-attribute
MX_SLP = 'MX24'

San Luis Potosi.

MX_SIN class-attribute instance-attribute
MX_SIN = 'MX25'

Sinaloa.

MX_SON class-attribute instance-attribute
MX_SON = 'MX26'

Sonora.

MX_TAB class-attribute instance-attribute
MX_TAB = 'MX27'

Tabasco.

MX_TAM class-attribute instance-attribute
MX_TAM = 'MX28'

Tamaulipas.

MX_TLA class-attribute instance-attribute
MX_TLA = 'MX29'

Tlaxcala.

MX_VER class-attribute instance-attribute
MX_VER = 'MX30'

Veracruz.

MX_YUC class-attribute instance-attribute
MX_YUC = 'MX31'

Yucatan.

MX_ZAC class-attribute instance-attribute
MX_ZAC = 'MX32'

Zacatecas.

Functions

state_country

state_country(state: NAState) -> str

Return the country name a state_id belongs to.

Used to reject a scope that pairs a subdivision with the wrong country, which the API would otherwise answer with an empty result set.

Source code in src/repeaterbook/na_states.py
def state_country(state: NAState) -> str:
    """Return the country name a ``state_id`` belongs to.

    Used to reject a scope that pairs a subdivision with the wrong country,
    which the API would otherwise answer with an empty result set.
    """
    if state.name.startswith("CA_"):
        return "Canada"
    if state.name.startswith("MX_"):
        return "Mexico"
    return "United States"

CSV export

Reads RepeaterBook's CSV export format into Repeater rows.

repeaterbook.csv_export

CSV export functionality for RepeaterBook.com data.

Classes

Functions

csv_row_to_model

csv_row_to_model(c: RepeaterCSV) -> Repeater

Convert CSV row to Repeater model.

Source code in src/repeaterbook/csv_export.py
def csv_row_to_model(c: RepeaterCSV, /) -> Repeater:
    """Convert CSV row to Repeater model."""
    d = Decimal

    def parse_tone(t: str) -> str | None:
        """Parse tone, return None if empty.

        The CSV spells "no tone" as "CSQ"; a blank cell is folded to None as
        well so the field is spelled the same way as on the JSON path.
        """
        return None if t in {"", "CSQ"} else t

    return Repeater.model_validate(
        Repeater(
            callsign=c["Callsign"] or None,
            frequency=d(c["Frequency (MHz)"]),
            input_frequency=d(c["Input Frequency (MHz)"]),
            pl_ctcss_uplink=parse_tone(c["Tone"]),
            location_nearest_city=c["City"],
            county=c["County"] or None,
            state=c["State"] or None,
            country=c["Country"] or None,
            landmark=c["Landmark"] or None,
            latitude=d(c["Latitude"]),
            longitude=d(c["Longitude"]),
            # Tri-state: the CSV leaves these blank outside North America, and
            # blank is "unknown", not "not supported".
            ares=parse_yes_no(c["ARES"]),
            races=parse_yes_no(c["RACES"]),
            skywarn=parse_yes_no(c["SKYWARN"]),
            canwarn=parse_yes_no(c["CANWARN"]),
            allstar_node=c["AllStar Node"] or None,
            echolink_node=c["EchoLink Node"] or None,
            irlp_node=c["IRLP Node"] or None,
            wires_node=c["WIRES-X Node"] or None,
            # Two-state, same decoder as the JSON path. The CSV spells "not
            # supported" as a blank cell rather than "No"; `parse_flag`'s
            # default covers that, so both exports land on False.
            analog_capable=parse_flag(c["FM (analog)"]),
            dmr_capable=parse_flag(c["DMR"]),
            dmr_color_code=c["DMR Color Code"] or None,
            d_star_capable=parse_flag(c["D-STAR Node"]),
            nxdn_capable=parse_flag(c["NXDN"]),
            apco_p_25_capable=parse_flag(c["P25"]),
            p_25_nac=c["P25 NAC"] or None,
            tetra_capable=parse_flag(c["TETRA"]),
            yaesu_system_fusion_capable=parse_flag(c["System Fusion"]),
            m17_capable=parse_flag(c["M17"]),
            pl_ctcss_tsq_downlink=parse_tone(c["TSQ Tone"]),
            # MISSING:
            state_id="",
            repeater_id=0,
            region=None,
            precise=False,
            use_membership=Use.OPEN,
            operational_status=Status.ON_AIR,
            dmr_id=None,
            m17_can=None,
            tetra_mcc=None,
            tetra_mnc=None,
            ysf_digital_id_uplink=None,
            ysf_digital_id_downlink=None,
            ysf_dsc=None,
            fm_bandwidth=Decimal("25.0"),
            notes=None,
            last_update=datetime.now(UTC).date(),
        )
    )

csv_to_models

csv_to_models(file: TextIOBase) -> list[Repeater]

Convert CSV file to list of Repeater models.

CSV does not include repeater ID or state ID, so these fields are populated based on the order of the rows and the state field.

Source code in src/repeaterbook/csv_export.py
def csv_to_models(file: io.TextIOBase) -> list[Repeater]:
    """Convert CSV file to list of Repeater models.

    CSV does not include repeater ID or state ID, so these fields are populated based
    on the order of the rows and the state field.
    """
    reader = csv.DictReader(file)
    repeaters = [csv_row_to_model(cast("RepeaterCSV", row)) for row in reader]
    for i, repeater in enumerate(repeaters):
        repeater.state_id = f"{repeater.state or 'XX'}"
        repeater.repeater_id = i + 1
    return repeaters

MCP server

Requires the mcp extra. See the MCP Server guide for running it.

Server

Configuration and the agent-facing tool declarations.

repeaterbook.mcp.server

FastMCP server exposing RepeaterBook lookup tools to agents.

Classes

RepeaterBookSettings

Bases: BaseSettings

MCP server configuration, read from REPEATERBOOK_* environment variables.

Attributes
working_dir class-attribute instance-attribute
working_dir: Path = Path()

Where the SQLite DB and HTTP cache live. Created on first use.

app_contact class-attribute instance-attribute
app_contact: EmailStr | None = None

Contact address for the API User-Agent.

Leave unset: it defaults to the address registered for App #114, and the API matches an approved application's User-Agent literally, so any other value returns 403 ua_mismatch. Set it only when running your own separate registered application.

app_token instance-attribute
app_token: SecretStr

Per-user RepeaterBook API token.

Required: as of RepeaterBook's 2026-03-03 API policy every export needs an approved rbuapp_ token, and an unauthenticated request is refused with 401 auth_missing. Demanding it up front turns that into a startup error rather than a failure on the first tool call.

No application registration is needed. Log in to your RepeaterBook account, open https://www.repeaterbook.com/user/api_apps.php, find "RepeaterBook Python Client" (App #114), and generate a token for it.

Functions

sync_repeaters async

sync_repeaters(country: _Country = None, state: _State = None, region: _Region = None, modes: set[RepeaterMode] | None = None) -> service.SyncResult

Download repeaters for a region into the local store.

Scope the download as narrowly as you can. RepeaterBook caps a response at 3500 rows and gives no indication when it truncates, so large scopes quietly return partial data. The result flags this when it happens.

Source code in src/repeaterbook/mcp/server.py
@mcp.tool()
async def sync_repeaters(
    country: _Country = None,
    state: _State = None,
    region: _Region = None,
    modes: set[RepeaterMode] | None = None,
) -> service.SyncResult:
    """Download repeaters for a region into the local store.

    Scope the download as narrowly as you can. RepeaterBook caps a response at
    3500 rows and gives no indication when it truncates, so large scopes
    quietly return partial data. The result flags this when it happens.
    """
    ctx = _get_context()
    query = _build_query(country, state, region, modes)
    try:
        return await service.sync(ctx.api, ctx.db, query)
    except RepeaterBookUnauthorizedError as exc:
        # A token is required to start, so reaching here means the one we have
        # is wrong rather than absent: expired, revoked, or issued for another
        # application or User-Agent.
        msg = (
            f"RepeaterBook rejected the API token ({exc}). Check that "
            "REPEATERBOOK_APP_TOKEN is current and issued for this "
            "application."
        )
        raise ValueError(msg) from exc

search_repeaters async

search_repeaters(lat: Annotated[float, Field(ge=-90, le=90)], lon: Annotated[float, Field(ge=-180, le=180)], radius_km: Annotated[float, Field(gt=0)], country: _Country = None, state: _State = None, region: _Region = None, bands: set[BandName] | None = None, modes: set[RepeaterMode] | None = None, status: set[RepeaterStatus] | None = None, use: set[RepeaterUse] | None = None, *, refresh: bool = False) -> list[RepeaterSpec]

Find nearby repeaters as repeater-specs.

Searches the local store. When a country/state/region scope is given and the store holds nothing for it yet, the region is downloaded first. Pass refresh=True to force a re-download of an already-populated scope.

Source code in src/repeaterbook/mcp/server.py
@mcp.tool()
async def search_repeaters(  # noqa: PLR0913
    lat: Annotated[float, Field(ge=-90, le=90)],
    lon: Annotated[float, Field(ge=-180, le=180)],
    radius_km: Annotated[float, Field(gt=0)],
    country: _Country = None,
    state: _State = None,
    region: _Region = None,
    bands: set[BandName] | None = None,
    modes: set[RepeaterMode] | None = None,
    status: set[RepeaterStatus] | None = None,
    use: set[RepeaterUse] | None = None,
    *,
    refresh: bool = False,
) -> list[RepeaterSpec]:
    """Find nearby repeaters as repeater-specs.

    Searches the local store. When a country/state/region scope is given and
    the store holds nothing for it yet, the region is downloaded first. Pass
    `refresh=True` to force a re-download of an already-populated scope.
    """
    ctx = _get_context()
    scoped = bool(country or state or region)
    # Syncing re-parses the whole regional payload and re-merges thousands of
    # rows, so don't do it on every search: only when asked, or when we have
    # nothing to search.
    empty = not await to_thread.run_sync(ctx.db.query)
    if scoped and (refresh or empty):
        await sync_repeaters(country, state, region, modes)
    elif empty:
        msg = "no local data; provide a country/region or call sync_repeaters first"
        raise ValueError(msg)

    def _search() -> list[RepeaterSpec]:
        return service.search(
            ctx.db,
            LatLon(lat, lon),
            radius_km,
            bands=bands,
            modes=modes,
            statuses=status,
            uses=use,
        )

    # SQLite reads plus a haversine pass over every row: run it off the event
    # loop so concurrent tool calls aren't blocked.
    return await to_thread.run_sync(_search)

get_repeater async

get_repeater(source_id: str) -> list[RepeaterSpec]

Return repeater-specs for a single repeater by its source id.

Source code in src/repeaterbook/mcp/server.py
@mcp.tool()
async def get_repeater(source_id: str) -> list[RepeaterSpec]:
    """Return repeater-specs for a single repeater by its source id."""
    ctx = _get_context()
    return await to_thread.run_sync(service.get_by_id, ctx.db, source_id)

clear_local_data async

clear_local_data() -> service.ClearResult

Delete everything stored locally: the repeater store and the API response cache.

Use this to start clean or to force the next sync to download fresh data from RepeaterBook. Both stores are cleared together on purpose: emptying only the repeater store would let the next sync refill it from a cached response, so the "fresh" data would be the same data. Nothing is lost that cannot be downloaded again. Afterwards, search_repeaters needs a scope (or a prior sync_repeaters) before it can return anything.

Source code in src/repeaterbook/mcp/server.py
@mcp.tool(
    annotations=ToolAnnotations(
        # Not read-only, and there is no undo: tell a client that asks before
        # running destructive tools to ask here. Idempotent, because a second
        # call finds nothing to remove; closed-world, because it touches only
        # files this server wrote.
        destructiveHint=True,
        idempotentHint=True,
        openWorldHint=False,
    )
)
async def clear_local_data() -> service.ClearResult:
    """Delete everything stored locally: the repeater store and the API response cache.

    Use this to start clean or to force the next sync to download fresh data
    from RepeaterBook. Both stores are cleared together on purpose: emptying
    only the repeater store would let the next sync refill it from a cached
    response, so the "fresh" data would be the same data. Nothing is lost that
    cannot be downloaded again. Afterwards, `search_repeaters` needs a scope
    (or a prior `sync_repeaters`) before it can return anything.
    """
    ctx = _get_context()
    return await service.clear(ctx.api, ctx.db)

main

main() -> None

Run the MCP server over stdio.

Builds the shared context up front so a missing or malformed REPEATERBOOK_APP_TOKEN surfaces as a startup failure. Deferring it to the first tool call would let the server advertise tools it cannot serve, reporting the misconfiguration as a per-call error instead.

Source code in src/repeaterbook/mcp/server.py
def main() -> None:  # pragma: no cover - process entry point
    """Run the MCP server over stdio.

    Builds the shared context up front so a missing or malformed
    ``REPEATERBOOK_APP_TOKEN`` surfaces as a startup failure. Deferring it to
    the first tool call would let the server advertise tools it cannot serve,
    reporting the misconfiguration as a per-call error instead.
    """
    _get_context()
    mcp.run()

Service

The orchestration layer the tools delegate to.

repeaterbook.mcp.service

Service layer orchestrating the RepeaterBook library for the MCP tools.

Classes

SyncResult

Bases: BaseModel

Outcome of a sync, including whether the API truncated the response.

ClearResult

Bases: BaseModel

Outcome of clearing the local data: what was removed from where.

Functions

sync async

sync(api: RepeaterBookAPI, db: RepeaterBook, query: ExportQuery) -> SyncResult

Download repeaters for a query and merge them into the local DB.

Source code in src/repeaterbook/mcp/service.py
async def sync(
    api: RepeaterBookAPI,
    db: RepeaterBook,
    query: ExportQuery,
) -> SyncResult:
    """Download repeaters for a query and merge them into the local DB."""
    skipped: list[RepeaterBookRowError] = []
    repeaters = await api.download(query, skipped=skipped)
    db.populate(repeaters)
    # The API caps a response and says nothing about it, so a query at the
    # limit has almost certainly lost rows. The library logs this, but a log
    # line is invisible to an MCP caller: report it in the result instead.
    # Count against rows served, not rows modelled: a skipped row still
    # consumed a slot against the cap, so using len(repeaters) here would
    # under-report truncation for any capped response containing a bad row.
    truncated = len(repeaters) + len(skipped) >= api.max_count
    return SyncResult(
        count=len(repeaters),
        truncated=truncated,
        skipped=len(skipped),
        detail=(
            f"RepeaterBook returned {len(repeaters) + len(skipped)} rows, its "
            "per-response limit, so this scope is very likely incomplete. "
            "Narrow it (for the US, Canada and Mexico, sync one state at a "
            "time)."
            if truncated
            else None
        ),
    )

clear async

clear(api: RepeaterBookAPI, db: RepeaterBook) -> ClearResult

Empty the local store and the API response cache together.

The two are separate on disk and clearing only the store is a trap: a response younger than max_cache_age (an hour by default) would be served again on the next sync, refilling the store with exactly the data the caller just asked to be rid of. Clearing both is the only way to make the next sync a genuine download.

Idempotent and safe on a never-populated working directory: nothing to clear reports as zeros rather than failing.

Source code in src/repeaterbook/mcp/service.py
async def clear(api: RepeaterBookAPI, db: RepeaterBook) -> ClearResult:
    """Empty the local store and the API response cache together.

    The two are separate on disk and clearing only the store is a trap: a
    response younger than `max_cache_age` (an hour by default) would be served
    again on the next sync, refilling the store with exactly the data the
    caller just asked to be rid of. Clearing both is the only way to make the
    next sync a genuine download.

    Idempotent and safe on a never-populated working directory: nothing to
    clear reports as zeros rather than failing.
    """
    # Cache first, so that a failure there leaves the store intact: an
    # inconsistent "cleared" state is worse than a fully reported failure.
    cached_responses = await api.clear_cache()
    # A blocking SQLite write; keep it off the event loop like the other
    # database calls the tools make.
    repeaters = await to_thread.run_sync(db.truncate)
    return ClearResult(repeaters=repeaters, cached_responses=cached_responses)

search

search(db: RepeaterBook, origin: LatLon, radius_km: float, *, bands: set[BandName] | None = None, modes: set[RepeaterMode] | None = None, statuses: set[RepeaterStatus] | None = None, uses: set[RepeaterUse] | None = None) -> list[RepeaterSpec]

Search the local DB and return distance-sorted repeater-specs.

Source code in src/repeaterbook/mcp/service.py
def search(  # noqa: PLR0913 - keyword-only filters mirror the MCP tool's params
    db: RepeaterBook,
    origin: LatLon,
    radius_km: float,
    *,
    bands: set[BandName] | None = None,
    modes: set[RepeaterMode] | None = None,
    statuses: set[RepeaterStatus] | None = None,
    uses: set[RepeaterUse] | None = None,
) -> list[RepeaterSpec]:
    """Search the local DB and return distance-sorted repeater-specs."""
    radius = Radius(origin, radius_km, Unit.KILOMETERS)
    where = [square(radius)]
    if bands:
        where.append(band(*(band_of(b) for b in bands)))

    rows = db.query(*where)
    nearby = filter_radius(rows, radius)

    # The DB stores the core Status/Use enums; the wire vocabulary is the
    # spec's StrEnums. Translate the filters once, up front, rather than
    # per row.
    status_set = {Status[s.name] for s in statuses} if statuses else None
    use_set = {Use[u.name] for u in uses} if uses else None

    specs: list[RepeaterSpec] = []
    for rep in nearby:
        if status_set is not None and rep.operational_status not in status_set:
            continue
        if use_set is not None and rep.use_membership not in use_set:
            continue
        distance = haversine(
            origin, (float(rep.latitude), float(rep.longitude)), unit=Unit.KILOMETERS
        )
        specs.extend(
            spec
            for spec in repeater_to_specs(rep, distance_km=Decimal(str(distance)))
            if modes is None or spec.mode in modes
        )
    return specs

get_by_id

get_by_id(db: RepeaterBook, source_id: str) -> list[RepeaterSpec]

Return repeater-specs for a single repeater by its source id.

Source code in src/repeaterbook/mcp/service.py
def get_by_id(db: RepeaterBook, source_id: str) -> list[RepeaterSpec]:
    """Return repeater-specs for a single repeater by its source id."""
    state_id, _, raw_id = source_id.partition(":")
    if not raw_id.isdigit():
        return []
    rows = db.query(
        Repeater.state_id == state_id,
        Repeater.repeater_id == int(raw_id),
    )
    return [spec for rep in rows for spec in repeater_to_specs(rep)]