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¶
engine
cached
property
¶
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
¶
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
init_db
¶
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
populate
¶
Populate internal database.
Source code in src/repeaterbook/database.py
query
¶
Query the database.
Source code in src/repeaterbook/database.py
truncate
¶
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
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
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
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
RepeaterBookRowError
¶
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. |
Initialize a row error with the offending row and its label.
Source code in src/repeaterbook/exceptions.py
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
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¶
fusion
property
¶
System Fusion parameters, or None if not Fusion-capable.
emergency_services
property
¶
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 is within valid range.
Source code in src/repeaterbook/models.py
validate_longitude
classmethod
¶
Validate longitude is within valid range.
Source code in src/repeaterbook/models.py
validate_frequency
classmethod
¶
Validate frequency is positive.
Source code in src/repeaterbook/models.py
Models¶
The Repeater ORM row, the API's JSON TypedDicts, and ExportQuery.
repeaterbook.models
¶
Models.
Attributes¶
BOOL_MAP
module-attribute
¶
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¶
fusion
property
¶
System Fusion parameters, or None if not Fusion-capable.
emergency_services
property
¶
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 is within valid range.
Source code in src/repeaterbook/models.py
validate_longitude
classmethod
¶
Validate longitude is within valid range.
Source code in src/repeaterbook/models.py
validate_frequency
classmethod
¶
Validate frequency is positive.
Source code in src/repeaterbook/models.py
ExportJSON
¶
Bases: TypedDict
RepeaterBook API export response.
ExportErrorJSON
¶
Bases: TypedDict
RepeaterBook API export error response.
ExportBaseQuery
¶
ExportNorthAmericaQuery
¶
Bases: ExportBaseQuery
RepeaterBook API export North America query.
% - wildcard
ExportWorldQuery
¶
ExportQuery
¶
RepeaterBook API export query.
% - wildcard
Functions¶
parse_flag
¶
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"or1->True."No"or0->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 |
Source code in src/repeaterbook/models.py
parse_yes_no
¶
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
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 |
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¶
url_export_rest_of_world
property
¶
Rest of world (not north-america) export URL.
Functions¶
cache_dir
async
¶
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
clear_cache
async
¶
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
urls_export
¶
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
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 | |
export_json
async
¶
Export data for given URL.
Source code in src/repeaterbook/services.py
export_multi_json
async
¶
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 |
False
|
skipped
|
list[RepeaterBookRowError] | None
|
Optional list to collect a |
None
|
Returns:
| Type | Description |
|---|---|
list[Repeater]
|
The downloaded repeaters, minus any skipped rows. |
Raises:
| Type | Description |
|---|---|
RepeaterBookRowError
|
If |
Source code in src/repeaterbook/services.py
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
parse_date
¶
json_to_model
¶
Converts a JSON object to a Repeater model.
RepeaterBook export payloads vary slightly between endpoints.
exportROW.phpmay include extra keys likesponsor.export.php(North America) includes keys likeCounty/ARES/… and may omitRegion.
This function should be resilient to those differences.
Source code in src/repeaterbook/services.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
row_label
¶
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
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
|
False
|
skipped
|
list[RepeaterBookRowError] | None
|
Optional list to collect a |
None
|
Returns:
| Type | Description |
|---|---|
list[Repeater]
|
The successfully converted repeaters, in input order. |
Raises:
| Type | Description |
|---|---|
RepeaterBookRowError
|
If |
Source code in src/repeaterbook/services.py
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¶
engine
cached
property
¶
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
¶
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
init_db
¶
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
populate
¶
Populate internal database.
Source code in src/repeaterbook/database.py
query
¶
Query the database.
Source code in src/repeaterbook/database.py
truncate
¶
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
Functions¶
schema_fingerprint
¶
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
Queries¶
Composable filter builders and the radius search.
repeaterbook.queries
¶
Queries.
Classes¶
Band
¶
Bases: NamedTuple
Band.
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
¶
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
filter_radius
¶
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
band_of
¶
band
¶
Return a query for repeaters within a given band.
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
¶
Tone
¶
Bases: NamedTuple
A squelch tone for one signal direction: at most one of CTCSS or DCS.
Functions¶
repeater_spec_json_schema
¶
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
schema_path
¶
write_schema
¶
Regenerate the published JSON Schema from the model.
Source code in src/repeaterbook/spec.py
parse_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
parse_node_id
¶
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
freq_to_band
¶
Return the amateur band name for a frequency, or None if unknown.
Source code in src/repeaterbook/spec.py
repeater_to_specs
¶
Expand one repeater into one spec per supported mode.
Source code in src/repeaterbook/spec.py
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
¶
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(rin 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.longitudeis 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
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
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
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
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
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
¶
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. |
Initialize a row error with the offending row and its label.
Source code in src/repeaterbook/exceptions.py
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.
Functions¶
state_country
¶
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
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
¶
Convert CSV row to Repeater model.
Source code in src/repeaterbook/csv_export.py
csv_to_models
¶
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
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
¶
Where the SQLite DB and HTTP cache live. Created on first use.
app_contact
class-attribute
instance-attribute
¶
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
¶
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
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
get_repeater
async
¶
Return repeater-specs for a single repeater by its source id.
clear_local_data
async
¶
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
main
¶
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
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
¶
Download repeaters for a query and merge them into the local DB.
Source code in src/repeaterbook/mcp/service.py
clear
async
¶
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
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
get_by_id
¶
Return repeater-specs for a single repeater by its source id.