Skip to content
bcgovPublic

About

Python and command line tools for quick access to DataBC geo-data available via WFS

Topics

Resources

Code of conduct

Stars

35 stars

Watchers

4 watching

Forks

Repository files navigation

bcdata

Actions Status pypi

Python and command line tools for quick access to DataBC geo-data available via WFS.

There is a wealth of British Columbia geographic information available as open data, but most sources are available only via WFS - and the syntax to download WFS data via ogr2ogr and/or curl/wget can be awkward.

This tool attempts to simplify downloads of BC geographic data and smoothly integrate with PostGIS and Python GIS tools like geopandas. The tool only accesses geographic data available via WFS - for other BC open data, download the files directly with requests / curl / ogr2ogr / etc (or the bcdata R package).

If downloads are failing, consult the BCGov Data Systems and Services status monitor - this tool depends on BC Open Geospatial Web Services API at openmaps.gov.bc.ca and the BC Data Catalogue API.

Installation and dependencies

Install with pip:

$ pip install bcdata

The examples below that use ogr2ogr also need the GDAL command line tools.

Configuration

Table list cache

To reduce the volume of requests, the list of tables available via WFS (the WFS GetCapabilities response) is cached locally. Table schemas are not cached, they are requested once each time bcdata runs. Location of the cache defaults to ~/.bcdata but can be modified by setting the BCDATA_CACHE environment variable:

export BCDATA_CACHE=/path/to/bcdata_cache

The cache will automatically refresh after 30 days - force a cache refresh by deleting the files in the cache or the entire cache folder.

Usage

Tables are requested by name, in the form schema.table: the Object Name shown in the DataBC Catalogue (under Object Description), or listed by bcdata list. For example, for BC Airports the table is whse_imagery_and_base_maps.gsr_airports_svw. Names can be given in upper or lower case.

Python module

import bcdata

# get a feature as geojson
geojson = bcdata.get_data(
    'whse_imagery_and_base_maps.gsr_airports_svw',
    query="AIRPORT_NAME='Terrace (Northwest Regional) Airport'"
)
geojson
{'type': 'FeatureCollection', 'features': [{'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [833428.6, 1055402.5001]}, ...

# optionally, load data as a geopandas GeoDataFrame. Column types are set from the
# table schema, as for GeoParquet output: integers are pandas' nullable Int64 (they
# stay integers when there are nulls) and dates are datetime.date values
gdf = bcdata.get_data(
    'whse_imagery_and_base_maps.gsr_airports_svw',
    query="AIRPORT_NAME='Terrace (Northwest Regional) Airport'",
    as_gdf=True
)
gdf[["AIRPORT_NAME", "geometry"]]
                           AIRPORT_NAME                    geometry
0  Terrace (Northwest Regional) Airport  POINT (833428.6 1055402.5)

CLI

Commands available via the bcdata command line interface are documented with the --help option


$ bcdata --help

Usage: bcdata [OPTIONS] COMMAND [ARGS]...

Options:
  --version  Show the version and exit.
  --help     Show this message and exit.

Commands:
  bc2pg    Load a DataBC WFS layer to a postgres db (DEPRECATED: Load data to
           PostgreSQL with ogr2ogr instead - see
           https://github.com/bcgov/bcdata_py/blob/main/postgresql.md)
  cat      Write DataBC features to stdout as GeoJSON feature objects.
  dump     Write DataBC features to stdout as GeoJSON feature collection.
  info     Print basic metadata about a DataBC WFS layer as JSON.
  list     List DataBC layers available via WFS
  parquet  Write DataBC features to a GeoParquet 2.0 file.

bc2pg

$ bcdata bc2pg --help

Usage: bcdata bc2pg [OPTIONS] DATASET

  Load a DataBC WFS layer to a postgres db (DEPRECATED: Load data to
  PostgreSQL with ogr2ogr instead - see
  https://github.com/bcgov/bcdata_py/blob/main/postgresql.md)

Options:
  -db, --db_url TEXT              Target database url, defaults to
                                  $DATABASE_URL environment variable if set
  --table TEXT                    Destination table name
  --schema TEXT                   Destination schema name
  --geometry_type TEXT            Spatial type of geometry column
  --query TEXT                    A valid CQL or ECQL query
  --bounds TEXT                   Bounds: "left bottom right top" or "[left,
                                  bottom, right, top]". Coordinates are BC
                                  Albers (default) or --bounds_crs
  --bounds-crs, --bounds_crs TEXT
                                  CRS of provided bounds
  -c, --count INTEGER             Total number of features to load
  -k, --primary_key TEXT          Primary key of dataset
  -s, --sortby TEXT               Name of sort field
  -e, --schema_only               Create empty table from catalogue schema
  -a, --append                    Append to existing table
  -r, --refresh                   Truncate from existing table before load
  -t, --no_timestamp              Do not log download to bcdata.log
  -v, --verbose                   Increase verbosity.
  -q, --quiet                     Decrease verbosity.
  --help                          Show this message and exit.

cat

$ bcdata cat --help

Usage: bcdata cat [OPTIONS] DATASET

  Write DataBC features to stdout as GeoJSON feature objects.

Options:
  --query TEXT                    A valid CQL or ECQL query
  -c, --count INTEGER             Number of features to request and dump
  --bounds TEXT                   Bounds: "left bottom right top" or "[left,
                                  bottom, right, top]". Coordinates are BC
                                  Albers (default) or --bounds_crs
  --bounds-crs, --bounds_crs TEXT
                                  CRS of provided bounds
  --indent INTEGER                Indentation level for JSON output
  --compact / --not-compact       Use compact separators (',', ':').
  -s, --sortby TEXT               Name of sort field
  -l, --lowercase                 Write column/properties names as lowercase
  -m, --promote-to-multi          Promote features to multipart
  --typed                         Set property types from the table schema:
                                  dates as YYYY-MM-DD. Numbers are written as
                                  DataBC sends them
  -v, --verbose                   Increase verbosity.
  -q, --quiet                     Decrease verbosity.
  --help                          Show this message and exit.

dump

$ bcdata dump --help

Usage: bcdata dump [OPTIONS] DATASET

  Write DataBC features to stdout as GeoJSON feature collection.

    $ bcdata dump whse_imagery_and_base_maps.gsr_airports_svw
    $ bcdata dump whse_imagery_and_base_maps.gsr_airports_svw --query "AIRPORT_NAME='Victoria Harbour (Shoal Point) Heliport'"
    $ bcdata dump whse_imagery_and_base_maps.gsr_airports_svw --bounds xmin ymin xmax ymax

Options:
  --query TEXT                    A valid CQL or ECQL query
  -c, --count INTEGER             Number of features to request and dump
  --bounds TEXT                   Bounds: "left bottom right top" or "[left,
                                  bottom, right, top]". Coordinates are BC
                                  Albers (default) or --bounds_crs
  --bounds-crs, --bounds_crs TEXT
                                  CRS of provided bounds
  -s, --sortby TEXT               Name of sort field
  -l, --lowercase                 Write column/properties names as lowercase
  -m, --promote-to-multi          Promote features to multipart
  --typed                         Set property types from the table schema:
                                  dates as YYYY-MM-DD, whole numbers as
                                  integers
  -v, --verbose                   Increase verbosity.
  -q, --quiet                     Decrease verbosity.
  --help                          Show this message and exit.

info

$ bcdata info --help

Usage: bcdata info [OPTIONS] DATASET

  Print basic metadata about a DataBC WFS layer as JSON.

  Optionally print a single metadata item as a string.

Options:
  --indent INTEGER  Indentation level for JSON output
  --count           Print the count of features.
  --name            Print the table name of the dateset.
  --description     Print the description of the dateset.
  --primary-key     Print the primary key column of the dataset (empty if it
                    has none).
  -l, --lowercase   Print the table name, primary key and column names as
                    lowercase (as bcdata parquet and cat/dump --lowercase
                    write them)
  -v, --verbose     Increase verbosity.
  -q, --quiet       Decrease verbosity.
  --help            Show this message and exit.

list

$ bcdata list --help

Usage: bcdata list [OPTIONS]

  List DataBC layers available via WFS

Options:
  -r, --refresh    Refresh the cached list
  -l, --lowercase  Print table names as lowercase
  --help           Show this message and exit.

parquet

$ bcdata parquet --help

Usage: bcdata parquet [OPTIONS] DATASET

  Write DataBC features to a GeoParquet 2.0 file.

    $ bcdata parquet whse_imagery_and_base_maps.gsr_airports_svw
    $ bcdata parquet whse_imagery_and_base_maps.gsr_airports_svw -o s3://my-bucket/airports.parquet

  Features are spatially sorted (Hilbert curve) and geometries are stored in
  BC Albers using the native Parquet GEOMETRY type, with GeoParquet metadata.
  Column names are written as lowercase. Files are zstd compressed (level 15).

  The download is checked before writing: if the number of features received
  differs from the WFS count, or the primary key has duplicates, nothing is
  written and the command fails.

Options:
  -o, --out TEXT                  Output path or URI (eg
                                  s3://bucket/key.parquet). Defaults to
                                  <object_name>.parquet
  --query TEXT                    A valid CQL or ECQL query
  -c, --count INTEGER             Number of features to request
  --bounds TEXT                   Bounds: "left bottom right top" or "[left,
                                  bottom, right, top]". Coordinates are BC
                                  Albers (default) or --bounds_crs
  --bounds-crs, --bounds_crs TEXT
                                  CRS of provided bounds
  -s, --sortby TEXT               Name of sort field (defaults to the table's
                                  sort key)
  --row-group-size INTEGER RANGE  Maximum rows per parquet row group
                                  [default: 50000; x>=1]
  --no-check                      Write even if the download fails consistency
                                  checks (feature count, duplicate primary
                                  keys)
  -v, --verbose                   Increase verbosity.
  -q, --quiet                     Decrease verbosity.
  --help                          Show this message and exit.

CLI examples

Search the data listing for airports:

$ bcdata list | grep AIRPORTS
WHSE_IMAGERY_AND_BASE_MAPS.GSR_AIRPORTS_SVW

Describe a table:

$ bcdata info whse_imagery_and_base_maps.gsr_airports_svw --indent 2
{
  "description": "BC Airports identifies locations where aircraft may take-off and land. ...",
  "comments": "GSR_AIRPORTS_SVW is a spatially enabled layer comprising AIRPORTS ...",
  "schema": [
    {
      "column_comments": "CUSTODIAN_ORG_DESCRIPTION contains the name or description of the custodial organization (usually Ministry and Branch)",
      "column_name": "CUSTODIAN_ORG_DESCRIPTION",
      "data_precision": 200,
      "data_type": "VARCHAR2",
      "short_name": "CUST_ORG"
    },
    ...etc...
  ],
  "primary_key": null,
  "catalogue": {
    "title": "BC Airports",
    "url": "https://catalogue.data.gov.bc.ca/dataset/bc-airports",
    "license": {
      "title": "Open Government Licence - British Columbia",
      "url": "https://www2.gov.bc.ca/gov/content?id=A519A56BC2BF44E4A008B33FCF527F61"
    },
    "publisher": "GeoBC Branch"
  },
  "name": "WHSE_IMAGERY_AND_BASE_MAPS.GSR_AIRPORTS_SVW",
  "count": 451
}

The JSON output can be manipulated with jq. For example, to list the columns of the table:

$ bcdata info whse_imagery_and_base_maps.gsr_airports_svw | jq -r '.schema[].column_name'
CUSTODIAN_ORG_DESCRIPTION
BUSINESS_CATEGORY_CLASS
BUSINESS_CATEGORY_DESCRIPTION
OCCUPANT_TYPE_DESCRIPTION
...etc...

Dump data as supplied by server (BC Albers):

$ bcdata dump whse_imagery_and_base_maps.gsr_airports_svw > airports.geojson

Dump data to geojson that conforms to RFC7946:

$ bcdata dump whse_imagery_and_base_maps.gsr_airports_svw | \
    ogr2ogr -f GeoJSON -lco RFC7946=YES /vsistdout/ /vsistdin/ > airports-4326.geojson

Load data to PostgreSQL with ogr2ogr, from files written by bcdata parquet, a bcdata cat stream, or the GeoParquet mirror: see postgresql.md. (bcdata bc2pg is deprecated.)

Projections / CRS

All data are as supplied from the server by default: BC Albers / EPSG:3005. Use some other tool to reproject the data as required.

Data License

Licenses vary by table: most are the Open Government Licence - British Columbia, but not all (eg whse_fish.pscis_remediation_svw is "Access Only"). Check the license of any table you use. bcdata info includes it, from the table's BC Data Catalogue record:

$ bcdata info whse_imagery_and_base_maps.gsr_airports_svw | jq '.catalogue.license'
{
  "title": "Open Government Licence - British Columbia",
  "url": "https://www2.gov.bc.ca/gov/content?id=A519A56BC2BF44E4A008B33FCF527F61"
}

Files written by bcdata parquet record it too, in their bcdata metadata.

Development and testing

Clone the repo:

$ git clone git@github.com:bcgov/bcdata_py.git
$ cd bcdata_py

bc2pg tests require a PostGIS database, referenced via the BCDATA_TEST_DATABASE_URL environment variable. Start one locally with docker (after editing the docker-compose.yml as needed):

$ docker compose build  # default to building the postgis image since official pre-built images are not available for all platforms
$ docker compose up -d
$ export BCDATA_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:8080/postgres

Install bcdata in development mode with uv:

$ uv sync --extra test
$ uv run pytest

Other implementations

About

Python and command line tools for quick access to DataBC geo-data available via WFS

Topics

Resources

Code of conduct

Stars

35 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages