Wait Time Canada API Reference¶
Overview¶
Wait Time Canada APIs are served from Next.js route handlers in frontend/app/api/.
Base URL:
- Local:
http://localhost:3000/api - Production:
<PRODUCTION_BASE_URL>/api(when deployed)
Conventions¶
- Most routes use JSON responses.
- Many routes return
{ success, data }for success and{ success: false, error, message }for errors. - Some older routes use payload-first contracts (kept for compatibility).
- Shared anonymous read routes use short cache windows to reduce repeated database reads on public routes.
Endpoint Catalog¶
Hospitals and comparability¶
GET /api/hospitals?province=ON[&page=1&limit=50]GET /api/hospitals/[slug]/trends?period=24h|7d|30d|90d|6m|1yGET /api/compare?a=<hospital_id>&b=<hospital_id>
System and data quality¶
GET /api/healthGET /api/data-quality?hospital_id=<id>&days=30GET /api/data-quality?view=trend&source_id=<source_id>&days=30GET /api/data-quality?view=diff&source_id=<source_id>&compare_days=7GET /api/anomalies?source_id=<source_id>&days=7
Invalid GET /api/data-quality query combinations now return 400 instead of silently falling back to the aggregate system view. In particular:
view=trendandview=diffrequiresource_idview=hospitalrequireshospital_idhospital_idandsource_idcannot be combined- bare
source_idwithoutview=trend|diffis rejected
Hospital listing note:
GET /api/hospitalsreturns all verified and visible hospitals by default so the map can render the full current inventory.pageandlimitare optional opt-in pagination controls;limitis capped at100.- Every successful response includes a national
coveragesnapshot withhospital_count,province_count,generated_at, andlatest_measurement_at. The top-levelcountremains the number of hospitals in the filtered or paginateddataarray.
Analytics¶
GET /api/analytics/benchmarks?province=ON&period=24h|7d|30d[&hospital_id=<id>]GET /api/analytics/trends?province=ON&period=weekly|monthly&lookback=3m|6m|1yGET /api/analytics/regions?province=ON&period=24h|7d|30dGET /api/analytics/patterns?hospital_id=<id>&type=hour_of_day|day_of_week|monthlyGET /api/analytics/occupancy?province=ONGET /api/analytics/equity-summary?province=ON&period=24h|7d|30d
Equity layer¶
GET /api/equity-layer?province=ON
Public health resources¶
GET /api/resources?kind=facility|aed[&q=<term>&province=ON&latitude=<lat>&longitude=<lng>&radius=<km>&limit=<n>]GET /api/resources/alerts?limit=<n>GET /api/resources/system-context?province=ON[&q=<term>&limit=<n>]GET /api/resources/water-advisories?province=ON[&q=<term>&limit=<n>]GET /api/resources/aqhi?latitude=<lat>&longitude=<lng>
Export¶
GET /api/export?format=csv|json&granularity=raw|hourly|daily|weekly|monthlygranularity=hourlyis derived from raw measurements and limited to 30-day windows- Methodology-aware export interpretation:
docs/research/export-methodology-interpretation-guide.md
Additional optional export params:
provincestart_dateend_dateinclude_methodology=true|falsepage_size(raw only; integer from 1 to 10,000, default 10,000)cursor(raw only; opaque cursor returned by the preceding page)
Data terms and attribution¶
The MIT licence covers the software. Exported values come from third-party sources and remain subject to each source's own terms; Wait Time Canada does not grant a licence to them. Check each source's terms before reusing or redistributing exported data.
Every export reports this:
- JSON:
metadata.data_terms(notice,software_license,data_license_granted: false) andmetadata.sources, one entry per source in the export withsource_id,source_name,source_urlandmethodology_url. - CSV:
source_name,source_urlandmethodology_urlcolumns on every row. The CSV body has no terms comment line, so it stays machine-readable; the terms are in theX-Data-Termsheader and in this documentation. - Headers:
X-Data-Terms. (X-Data-Licenseandmetadata.licensewere removed; they previously and incorrectly saidCC-BY-4.0.)
Source names and URLs come from the current source catalog.
Raw measurement exports include each row's stored source_id, raw_payload_hash, and parser_version; raw_payload_snippet is never exposed. source_name, source_url and methodology_url are joined from the current source catalog, so they are not a historical snapshot of source metadata. Aggregate exports may identify their aggregate source, but do not include per-measurement hashes or parser versions.
Raw measurements are ordered by descending (timestamp_utc, measurement ID) and use keyset pagination. JSON metadata describes the current page, including record_count, page_size, has_more, is_complete, next_cursor, and next_url; methodology_homogeneity also describes only that page. is_complete means no additional matching row was reported at request time; it does not indicate a complete archive. CSV and JSON responses expose X-Export-Record-Count, X-Export-Page-Size, X-Export-Has-More, and X-Export-Complete; when another page exists, they also provide X-Export-Next-Cursor and a Link header with rel="next". The cursor is bound to the province/date filters, format, methodology-column choice, and page size. Changing those values requires starting without the cursor.
Raw export timestamps remain strings in UTC ISO 8601 form with six fractional- second digits (YYYY-MM-DDTHH:mm:ss.ffffffZ), preserving microsecond precision for output, date bounds, and cursor comparisons. Each page is a separate request, not a transactionally consistent snapshot. Concurrent inserts or deletes can change which rows are observed across pages; page metadata does not claim a complete archive. The page size limits returned rows, not the amount of data a database may inspect or sort. Pagination applies only to granularity=raw; hourly and pre-aggregated exports retain their existing 10,000-result cap and do not return pagination metadata.
Geolocation¶
GET /api/geolocation
Admin verification¶
GET /api/admin/hospitals/unverifiedPOST /api/admin/hospitals/[id]/verifyDELETE /api/admin/hospitals/[id]/verify
Key Contracts¶
Response caching and transfer guardrails¶
These routes use endpoint-specific caching contracts on the public frontend path:
GET /api/health: 60-second in-process read cache withCache-Control: no-store; browser status components poll every 5 minutes while visibleGET /api/status: 5-minute in-process and shared-cache window, with a 15-minute stale-while-revalidate allowanceGET /api/hospitals:Cache-Control: no-store; the application may coalesce identical reads in-process for no more than 30 secondsGET /api/analytics/occupancy:Cache-Control: no-store; the endpoint bypasses application response caching so source-health changes are reflected without an application cache windowGET /api/resources,GET /api/resources/alerts,GET /api/resources/system-context,GET /api/data-quality,GET /api/anomalies,GET /api/compare,GET /api/analytics/benchmarks,GET /api/analytics/trends,GET /api/analytics/regions,GET /api/analytics/equity-summary, andGET /api/analytics/patterns: 5-minute shared cache windowGET /api/methodology: 1-minute shared cache window-
GET /api/hospitals/[slug]/trends: 10-minute shared cache window -
Read-heavy routes can also use short-lived in-process response caching without changing data collection or storage policy.
GET /api/geolocationandGET /api/exportremainCache-Control: no-store.GET /api/resources/aqhiuses a 15-minute shared cache window with a live upstream fetch behind the server cache.GET /api/resources/water-advisoriesuses a 1-hour shared cache window with a live upstream fetch behind the server cache.
Health endpoint operational contract (M30)¶
GET /api/health remains backward-compatible and now includes structured scraper diagnostics.
Top-level fields:
healthy: booleandatabase: { status, latency_ms, pool_status }last_update: string | nullstale_threshold_minutes: numbersources: SourceHealth[]
Operational note:
- The live stale threshold is currently
120minutes, supplied by environment/config but exposed directly in the response so operators and clients can stay aligned.
Per-source diagnostics (SourceHealth) include:
- Existing:
source_id,source_name,last_run,status,error_message,measurements_count,age_minutes - Added:
last_success_run,last_success_measurements_count,last_error_run,last_error_category,last_error_stage,consecutive_failures,last_run_duration_ms
Failure categories currently emitted by backend heartbeat/classification logic:
upstream_unavailableparser_breakageinfra_runtimepersistence_failureunknown
Status and data-quality KPI cadence (D12)¶
GET /api/status and the aggregate GET /api/data-quality view now compute public KPI percentages against the active live scraper set only:
quebec-msssontario-healthalberta-ahsbc-phsa
Operational note:
- these aggregate percentages now reflect the current hourly scraper expectation model (
24expected runs/day), not the older 15-minute expectation model /api/status.overall_statusgrades 24-hour measurement-hour completeness, not current source freshness. The response makes this explicit withoverall_status_basis=measurement_hour_completeness_24handmeasurement_window_timezone=UTC;/api/health.healthyremains the current database/heartbeat freshness signal. A fresh source can therefore coexist with a critical 24-hour completeness grade after missed earlier hours.- hospital-level scrape counts and success rates are computed from distinct UTC hourly scrape windows, not raw measurement-row counts
- aggregate measurement counts are returned as actual counts, not reconstructed from percentage estimates
- historical
view=trend/view=diffresponses now includehistorical_annotationmetadata when the requested snapshot range spans both the legacy 15-minute expectation model (96expected runs/day) and the current hourly model (24expected runs/day) - the public
/data-qualitypage renders that annotation directly instead of implying long-range snapshot comparability that the historical records do not fully support
Comparability endpoint¶
GET /api/compare returns:
comparable: boolean;trueonly when both hospitals have a current value and identical methodologydivergence_brief: string | null- methodology fields for both hospitals
- per hospital:
wait_time(non-null only when the value is current),monthly_average_minutes,wait_time_status, andlast_updated(see Wait-time freshness contract)
Wait-time freshness contract¶
GET /api/hospitals and GET /api/compare only return a wait time as a current value when the hospital's own latest TIME_TO_PROVIDER measurement is recent for its source. Each hospital carries wait_time_status:
wait_time_status | Meaning | Value fields |
|---|---|---|
current | Live-estimate source and the measurement is within the cutoff | current_wait_time (wait_time on compare) |
stale | Live-estimate source and the measurement is older than cutoff | none; last_updated is the date of the last report |
monthly | Monthly source (Ontario Health); never current | monthly_average_minutes; last_updated is when it was last read |
none | No measurement | none |
Cutoffs (utils/wait-time-freshness.ts): Alberta (alberta-ahs), BC (bc-phsa) and Quebec (quebec-msss) are collected hourly, and a value is current for up to 120 minutes (two collection intervals, the same threshold as the source heartbeat check). The boundary is inclusive. Missing, unparsable or future timestamps are stale, and an unrecognised source uses the same 120 minute cutoff. Ontario Health publishes a monthly average, so it is always monthly; the reporting period is not stored, and last_updated is the time of the collector run, not the period the figure covers.
Compare responses are cached for up to five minutes, so a value can remain current for up to five minutes past the cutoff.
Occupancy keeps its separate fail-closed contract (see below).
Public health resource contracts¶
GET /api/resources returns:
successcountdatameta.kindmeta.querymeta.source_statusmeta.source_catalog
GET /api/resources/alerts returns:
successcountdatameta.limitmeta.source_statusmeta.source_catalog
GET /api/resources/system-context returns:
successdata.dispatch_centresdata.paramedic_servicesmeta.querymeta.scopemeta.source_statusmeta.source_catalog
GET /api/resources/water-advisories returns:
successcountdatameta.querymeta.scopemeta.summarymeta.source_statusmeta.source_catalog
GET /api/resources/aqhi returns:
successdata(AQHIRecord | null)meta.latitudemeta.longitudemeta.source_statusmeta.source_catalog
Each source_status row includes:
source_idsource_nameprovenance_urllast_refreshed_atfreshness_state(show | warn | suppress)
Each source_catalog row includes:
source_iddomainsource_nameconnector_typeaccess_routelicense_reuse_statusattribution_requirementupdate_cadencerecommended_usage_modepublic_methodology_noteprovenance_urllast_verified_atlast_refreshed_atfreshness_state
Operational note:
- Facility rows are reference-directory data only and should not be interpreted as live operational availability.
- AED rows are OSM-backed fallback data and remain explicitly crowdsourced/incomplete.
- Ontario EMS system-context rows are background context only and should not be interpreted as live dispatch availability or routing guidance.
- Ontario drinking-water advisories are scoped to active long-term advisories on public systems on reserve and should not be interpreted as a complete map of all Ontario water advisories.
- AQHI responses may intentionally return
data: nullwhen the upstream source freshness state issuppress.
Occupancy availability contract¶
GET /api/analytics/occupancy returns one of:
status: "available"status: "no_reporting_data"status: "not_available_yet"
This ensures missing source fields are explicit, not silently treated as zero.
status: "available" requires both a fresh occupancy observation and a healthy, fresh heartbeat from the matching source. Sources with failed, stale, future-dated, or missing heartbeats are omitted independently. In provinces with more than one source, observations from all remaining eligible sources are still aggregated over the documented reporting window.
Equity availability contract¶
GET /api/analytics/equity-summary returns one of:
status: "ready"status: "no_reporting_data"status: "not_available_yet"
When status: "ready", the payload also includes:
sensitivity_analysis(threshold table, default 10/20/30/40 km)uncertainty(bootstrap percentile 95% intervals, descriptive only)methodologymetadata including:interpretation: "descriptive_association_only"causal_inference: falsecensus_income_reference_yearwait_aggregation_period- temporal alignment note
GET /api/equity-layer returns setup guidance when province data is not scaffolded yet, and for successful ON responses includes metadata:
reference_yearinterpretationcausal_inferencetemporal_alignment_notesource_fileoptimized_geometry
Layer loading behavior is optimized-first with canonical fallback:
ontario-equity-layer.optimized.geojson(preferred when present)ontario-equity-layer.geojson(fallback)
Analytics freshness notes¶
GET /api/analytics/patterns?type=hour_of_dayderives its hourly view from bounded raw measurements rather than precomputed hourly aggregates.GET /api/export?granularity=hourlyis intended for bounded recent windows only and returns an error for oversized hourly requests.
Example Requests¶
# Hospitals in Ontario
curl "http://localhost:3000/api/hospitals?province=ON"
# Compare two hospitals
curl "http://localhost:3000/api/compare?a=ca-on-ottawa-general&b=ca-qc-chum"
# Benchmarks
curl "http://localhost:3000/api/analytics/benchmarks?province=ON&period=7d"
# Province trend
curl "http://localhost:3000/api/analytics/trends?province=ON&period=monthly&lookback=6m"
# Regions
curl "http://localhost:3000/api/analytics/regions?province=ON&period=7d"
# Export aggregated monthly data
curl "http://localhost:3000/api/export?format=json&granularity=monthly&province=ON"
Data Use and Interpretation¶
- Use methodology tags when interpreting or comparing hospitals.
- Do not interpret cross-province comparisons as directly comparable unless ontology dimensions match.
- This platform is informational and operational; it is not a triage or medical advice service.