environment-client


Nameenvironment-client JSON
Version 0.5.13 PyPI version JSON
download
home_pageNone
SummaryPython client for DEFRA's environment.data.gov.uk APIs (typed, async-friendly)
upload_time2025-10-09 11:34:31
maintainerNone
docs_urlNone
authorNone
requires_python>=3.12
licenseMIT License Copyright (c) 2025 cogna-public Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords api defra environment environment.data.gov.uk flood hydrology uk
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # DEFRA Environment Client 🌿

[![PyPI version](https://img.shields.io/pypi/v/environment-client.svg)](https://pypi.org/project/environment-client/)
[![GitHub Release](https://img.shields.io/github/v/release/cogna-public/environment-client?display_name=release)](https://github.com/cogna-public/environment-client/releases)
[![Publish Status](https://github.com/cogna-public/environment-client/actions/workflows/publish.yml/badge.svg)](https://github.com/cogna-public/environment-client/actions/workflows/publish.yml)
[![Python Versions](https://img.shields.io/pypi/pyversions/environment-client.svg)](https://pypi.org/project/environment-client/)
[![License: MIT](https://img.shields.io/pypi/l/environment-client.svg)](LICENSE)

Python client for DEFRA’s environment.data.gov.uk APIs — fast, typed, and async‑friendly. 🌟

## Installation 🧰

```bash
uv pip install environment-client
```

## Usage 🐍

```python
import asyncio
from environment.flood_monitoring import FloodClient
from environment.public_register import PublicRegisterClient


async def main():
    """
    An example of how to use the clients to get data from the APIs.
    """
    async with (
        FloodClient() as flood_client,
        PublicRegisterClient() as public_register_client,
    ):
        # Get flood warnings
        flood_warnings = await flood_client.get_flood_warnings()
        print(f"Found {len(flood_warnings)} flood warnings.")
        
        # Search for waste operations registrations
        waste_operations = await public_register_client.get_waste_operations(limit=5)
        print(f"Found {len(waste_operations.items)} waste operations.")
        
        # Search across all registers
        all_registrations = await public_register_client.search_all_registers(name_search="Limited", limit=5)
        print(f"Found {len(all_registrations.items)} registrations with 'Limited' in the name.")


if __name__ == "__main__":
    asyncio.run(main())
```

## Supported APIs 🌐

- Real-time Flood Monitoring (flood warnings, areas, stations, measures, readings)
- Bathing Waters
- Asset Management
- Hydrology
- Rainfall
- Water Quality Data Archive (WQA)
- Public Register (waste operations, end-of-life vehicles, industrial installations, water discharges, radioactive substances, waste carriers/brokers, waste exemptions, water discharge exemptions, scrap metal dealers, enforcement actions, flood risk exemptions)

## Package Name vs Import Path 🔤

- Distribution (PyPI): `environment-client`
- Import path (Python): `environment`

Example:

```python
from environment.flood_monitoring import FloodClient
```

Note: The distribution is named `environment-client` while the import path is `environment`. This keeps imports concise but clarifies the project scope on PyPI.

### ⚠️ Important: WQA API Replacement

Note: The Water Quality Archive (WQA) APIs will be replaced later this year, meaning that the existing APIs will no longer work after Spring/Summer 2025. As of now, many `water-quality/view` endpoints return HTTP 404. We’ve:

- Added a `DeprecationWarning` when instantiating `WaterQualityDataArchiveClient`.
- Marked WQA tests as `skipped` until the replacement API is available.

For updates, see DEFRA’s support pages:
https://environment.data.gov.uk/apiportal/support

## Implementation Status 📊

- Flood Monitoring
  - Base: `https://environment.data.gov.uk/flood-monitoring`
  - Implemented: `get_flood_warnings` (`/id/floods`), `get_flood_areas` (`/id/floodAreas`), `get_stations` (`/id/stations`), `get_station_by_id`, `get_measures` (`/id/measures`), `get_measure_by_id`, `get_readings` (`/data/readings`), `get_reading_by_id`.
  - Notes: Uses canonical `/id` for entities and `/data` for readings. Integration tests use VCR.

- Rainfall
  - Base: Flood Monitoring (parameterised)
  - Implemented: Stations and measures filtered with `parameter=rainfall`; readings via `/data/readings?parameter=rainfall`; reading-by-id via `/data/readings/{measure_id}/{timestamp}`.
  - Notes: Rainfall is part of Flood Monitoring; not a separate base path.

- Tide Gauge
  - Base: Flood Monitoring (typed)
  - Implemented: Stations via `/id/stations?type=TideGauge`, station-by-id, readings via `/data/readings?stationType=TideGauge`, reading-by-id via `/data/readings/{measure_id}/{timestamp}`.

- Hydrology
  - Base: `https://environment.data.gov.uk/hydrology`
  - Implemented: Stations, station-by-id, measures, measure-by-id, readings per-measure via `/id/measures/{id}/readings` (lists do not expose a global `/id/readings`).
  - Notes: Some fields (e.g., `status`, `riverName`, `station`, `unit`) are normalised for model compatibility.

- Bathing Waters
  - Base: `https://environment.data.gov.uk`
  - Implemented: `get_bathing_waters` (`/doc/bathing-water.json`), plus related entity lookups under `/id/*`.

- Asset Management
  - Base: `https://environment.data.gov.uk/asset-management`
  - Implemented: Assets, maintenance activities/tasks/plans, capital schemes (JSON endpoints under `/id/*.json`).

- Catchment Planning (Catchment Data)
  - Base: `https://environment.data.gov.uk/catchment-planning`
  - Status: Placeholder only (`get_catchment_data` returns `[]` until the correct endpoint is confirmed).

- Water Quality Data Archive (WQA)
  - Base: `https://environment.data.gov.uk/water-quality/view`
  - Status: Being replaced by DEFRA; many endpoints currently return HTTP 404. Client issues a `DeprecationWarning`. Tests are skipped until the replacement API is available.

## Testing & VCR 🧪

- Tests are recorded/replayed with `pytest-vcr` (record mode: once).
- Cassettes are stored under `tests/cassettes/` with per-module subfolders (e.g., `rainfall/`, `hydrology/`, `tide_gauge/`, `integration/`).
- To re-record a cassette, delete the corresponding YAML file and re-run the specific test.
- Integration tests also use VCR to avoid live network dependency.

## Development 🛠️

Contributing? See AGENTS.md for full repository guidelines (structure, style, testing, and PR conventions).

This project uses `uv` for dependency management.

- Install dependencies: `uv sync` or `just install`
- Run tests: `just test`
- Run integration tests: `just test-integration`
- Lint (fix): `just lint`
- Format: `just format`
- Example script: `just run-main`

## Contributing 🤝

- Start with AGENTS.md for repository structure, coding style, testing, and PR conventions.
- Open an issue for larger changes; link issues in PRs.
- Follow commit prefixes (e.g., `feat:`, `fix:`, `docs:`) and keep messages concise.
- Run `just lint`, `just format`, and `just test` before pushing. Update or re-record VCR cassettes when tests change network interactions.

## Releasing 🚀

### Automatic Releases (Default)

**Patch versions are released automatically!** Simply merge your PR to `main`:

1. Merge PR to `main`
2. GitHub Actions automatically:
   - Bumps patch version (e.g., 0.5.11 → 0.5.12)
   - Creates git tag and GitHub release
   - Publishes to PyPI via Trusted Publishing

**No manual steps required!** The workflow uses `uv version --bump patch` automatically.

### Manual Releases (Minor/Major versions)

For **minor** or **major** version bumps, use the Justfile recipe:

```bash
just release minor          # bump minor (0.5.x → 0.6.0)
just release major "Notes"  # bump major (0.5.x → 1.0.0)
```

**Requirements:**
- `gh` CLI authenticated (`gh auth status`)
- The recipe runs `uv version --bump`, commits changes, creates tag, and publishes

**Alternatively, run manually:**

```bash
uv version --bump minor  # or major
git add pyproject.toml uv.lock
git commit -m "publish: bump to vX.Y.Z"
git push origin main
git tag vX.Y.Z && git push origin vX.Y.Z
gh release create vX.Y.Z --title "vX.Y.Z" --notes "Release notes"
```

### How It Works

- **Automatic workflow:** `.github/workflows/auto-version.yml` bumps patch on every merge to main
- **Publishing workflow:** `.github/workflows/publish.yml` publishes to PyPI when releases are created
- **Trusted Publishing:** Uses GitHub's OIDC for PyPI (no manual tokens)

### Setup (First Time Only)

To enable automatic PyPI publishing, you need a **Personal Access Token (PAT)**:

1. Create a fine-grained PAT: GitHub Settings → Developer settings → Personal access tokens
2. Grant it `Contents: Read and write` permission for this repository
3. Add it as a repository secret named `PAT_TOKEN`

**Why?** GitHub's default token doesn't trigger other workflows. The PAT allows the version bump to trigger PyPI publishing.

**Without PAT:** Version bump still works, but you'll need to manually trigger the publish workflow.

**Links:**
- PyPI project: https://pypi.org/project/environment-client/
- Workflow setup guide: `.github/workflows/README.md`

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "environment-client",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": null,
    "keywords": "api, defra, environment, environment.data.gov.uk, flood, hydrology, uk",
    "author": null,
    "author_email": "\"Cogna.co\" <engineering@cogna.co>",
    "download_url": "https://files.pythonhosted.org/packages/f9/63/68faa5c6db988a73b20c3028ff1787db3d1e69ec17bd32f190cb5933ab3e/environment_client-0.5.13.tar.gz",
    "platform": null,
    "description": "# DEFRA Environment Client \ud83c\udf3f\n\n[![PyPI version](https://img.shields.io/pypi/v/environment-client.svg)](https://pypi.org/project/environment-client/)\n[![GitHub Release](https://img.shields.io/github/v/release/cogna-public/environment-client?display_name=release)](https://github.com/cogna-public/environment-client/releases)\n[![Publish Status](https://github.com/cogna-public/environment-client/actions/workflows/publish.yml/badge.svg)](https://github.com/cogna-public/environment-client/actions/workflows/publish.yml)\n[![Python Versions](https://img.shields.io/pypi/pyversions/environment-client.svg)](https://pypi.org/project/environment-client/)\n[![License: MIT](https://img.shields.io/pypi/l/environment-client.svg)](LICENSE)\n\nPython client for DEFRA\u2019s environment.data.gov.uk APIs \u2014 fast, typed, and async\u2011friendly. \ud83c\udf1f\n\n## Installation \ud83e\uddf0\n\n```bash\nuv pip install environment-client\n```\n\n## Usage \ud83d\udc0d\n\n```python\nimport asyncio\nfrom environment.flood_monitoring import FloodClient\nfrom environment.public_register import PublicRegisterClient\n\n\nasync def main():\n    \"\"\"\n    An example of how to use the clients to get data from the APIs.\n    \"\"\"\n    async with (\n        FloodClient() as flood_client,\n        PublicRegisterClient() as public_register_client,\n    ):\n        # Get flood warnings\n        flood_warnings = await flood_client.get_flood_warnings()\n        print(f\"Found {len(flood_warnings)} flood warnings.\")\n        \n        # Search for waste operations registrations\n        waste_operations = await public_register_client.get_waste_operations(limit=5)\n        print(f\"Found {len(waste_operations.items)} waste operations.\")\n        \n        # Search across all registers\n        all_registrations = await public_register_client.search_all_registers(name_search=\"Limited\", limit=5)\n        print(f\"Found {len(all_registrations.items)} registrations with 'Limited' in the name.\")\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n## Supported APIs \ud83c\udf10\n\n- Real-time Flood Monitoring (flood warnings, areas, stations, measures, readings)\n- Bathing Waters\n- Asset Management\n- Hydrology\n- Rainfall\n- Water Quality Data Archive (WQA)\n- Public Register (waste operations, end-of-life vehicles, industrial installations, water discharges, radioactive substances, waste carriers/brokers, waste exemptions, water discharge exemptions, scrap metal dealers, enforcement actions, flood risk exemptions)\n\n## Package Name vs Import Path \ud83d\udd24\n\n- Distribution (PyPI): `environment-client`\n- Import path (Python): `environment`\n\nExample:\n\n```python\nfrom environment.flood_monitoring import FloodClient\n```\n\nNote: The distribution is named `environment-client` while the import path is `environment`. This keeps imports concise but clarifies the project scope on PyPI.\n\n### \u26a0\ufe0f Important: WQA API Replacement\n\nNote: The Water Quality Archive (WQA) APIs will be replaced later this year, meaning that the existing APIs will no longer work after Spring/Summer 2025. As of now, many `water-quality/view` endpoints return HTTP 404. We\u2019ve:\n\n- Added a `DeprecationWarning` when instantiating `WaterQualityDataArchiveClient`.\n- Marked WQA tests as `skipped` until the replacement API is available.\n\nFor updates, see DEFRA\u2019s support pages:\nhttps://environment.data.gov.uk/apiportal/support\n\n## Implementation Status \ud83d\udcca\n\n- Flood Monitoring\n  - Base: `https://environment.data.gov.uk/flood-monitoring`\n  - Implemented: `get_flood_warnings` (`/id/floods`), `get_flood_areas` (`/id/floodAreas`), `get_stations` (`/id/stations`), `get_station_by_id`, `get_measures` (`/id/measures`), `get_measure_by_id`, `get_readings` (`/data/readings`), `get_reading_by_id`.\n  - Notes: Uses canonical `/id` for entities and `/data` for readings. Integration tests use VCR.\n\n- Rainfall\n  - Base: Flood Monitoring (parameterised)\n  - Implemented: Stations and measures filtered with `parameter=rainfall`; readings via `/data/readings?parameter=rainfall`; reading-by-id via `/data/readings/{measure_id}/{timestamp}`.\n  - Notes: Rainfall is part of Flood Monitoring; not a separate base path.\n\n- Tide Gauge\n  - Base: Flood Monitoring (typed)\n  - Implemented: Stations via `/id/stations?type=TideGauge`, station-by-id, readings via `/data/readings?stationType=TideGauge`, reading-by-id via `/data/readings/{measure_id}/{timestamp}`.\n\n- Hydrology\n  - Base: `https://environment.data.gov.uk/hydrology`\n  - Implemented: Stations, station-by-id, measures, measure-by-id, readings per-measure via `/id/measures/{id}/readings` (lists do not expose a global `/id/readings`).\n  - Notes: Some fields (e.g., `status`, `riverName`, `station`, `unit`) are normalised for model compatibility.\n\n- Bathing Waters\n  - Base: `https://environment.data.gov.uk`\n  - Implemented: `get_bathing_waters` (`/doc/bathing-water.json`), plus related entity lookups under `/id/*`.\n\n- Asset Management\n  - Base: `https://environment.data.gov.uk/asset-management`\n  - Implemented: Assets, maintenance activities/tasks/plans, capital schemes (JSON endpoints under `/id/*.json`).\n\n- Catchment Planning (Catchment Data)\n  - Base: `https://environment.data.gov.uk/catchment-planning`\n  - Status: Placeholder only (`get_catchment_data` returns `[]` until the correct endpoint is confirmed).\n\n- Water Quality Data Archive (WQA)\n  - Base: `https://environment.data.gov.uk/water-quality/view`\n  - Status: Being replaced by DEFRA; many endpoints currently return HTTP 404. Client issues a `DeprecationWarning`. Tests are skipped until the replacement API is available.\n\n## Testing & VCR \ud83e\uddea\n\n- Tests are recorded/replayed with `pytest-vcr` (record mode: once).\n- Cassettes are stored under `tests/cassettes/` with per-module subfolders (e.g., `rainfall/`, `hydrology/`, `tide_gauge/`, `integration/`).\n- To re-record a cassette, delete the corresponding YAML file and re-run the specific test.\n- Integration tests also use VCR to avoid live network dependency.\n\n## Development \ud83d\udee0\ufe0f\n\nContributing? See AGENTS.md for full repository guidelines (structure, style, testing, and PR conventions).\n\nThis project uses `uv` for dependency management.\n\n- Install dependencies: `uv sync` or `just install`\n- Run tests: `just test`\n- Run integration tests: `just test-integration`\n- Lint (fix): `just lint`\n- Format: `just format`\n- Example script: `just run-main`\n\n## Contributing \ud83e\udd1d\n\n- Start with AGENTS.md for repository structure, coding style, testing, and PR conventions.\n- Open an issue for larger changes; link issues in PRs.\n- Follow commit prefixes (e.g., `feat:`, `fix:`, `docs:`) and keep messages concise.\n- Run `just lint`, `just format`, and `just test` before pushing. Update or re-record VCR cassettes when tests change network interactions.\n\n## Releasing \ud83d\ude80\n\n### Automatic Releases (Default)\n\n**Patch versions are released automatically!** Simply merge your PR to `main`:\n\n1. Merge PR to `main`\n2. GitHub Actions automatically:\n   - Bumps patch version (e.g., 0.5.11 \u2192 0.5.12)\n   - Creates git tag and GitHub release\n   - Publishes to PyPI via Trusted Publishing\n\n**No manual steps required!** The workflow uses `uv version --bump patch` automatically.\n\n### Manual Releases (Minor/Major versions)\n\nFor **minor** or **major** version bumps, use the Justfile recipe:\n\n```bash\njust release minor          # bump minor (0.5.x \u2192 0.6.0)\njust release major \"Notes\"  # bump major (0.5.x \u2192 1.0.0)\n```\n\n**Requirements:**\n- `gh` CLI authenticated (`gh auth status`)\n- The recipe runs `uv version --bump`, commits changes, creates tag, and publishes\n\n**Alternatively, run manually:**\n\n```bash\nuv version --bump minor  # or major\ngit add pyproject.toml uv.lock\ngit commit -m \"publish: bump to vX.Y.Z\"\ngit push origin main\ngit tag vX.Y.Z && git push origin vX.Y.Z\ngh release create vX.Y.Z --title \"vX.Y.Z\" --notes \"Release notes\"\n```\n\n### How It Works\n\n- **Automatic workflow:** `.github/workflows/auto-version.yml` bumps patch on every merge to main\n- **Publishing workflow:** `.github/workflows/publish.yml` publishes to PyPI when releases are created\n- **Trusted Publishing:** Uses GitHub's OIDC for PyPI (no manual tokens)\n\n### Setup (First Time Only)\n\nTo enable automatic PyPI publishing, you need a **Personal Access Token (PAT)**:\n\n1. Create a fine-grained PAT: GitHub Settings \u2192 Developer settings \u2192 Personal access tokens\n2. Grant it `Contents: Read and write` permission for this repository\n3. Add it as a repository secret named `PAT_TOKEN`\n\n**Why?** GitHub's default token doesn't trigger other workflows. The PAT allows the version bump to trigger PyPI publishing.\n\n**Without PAT:** Version bump still works, but you'll need to manually trigger the publish workflow.\n\n**Links:**\n- PyPI project: https://pypi.org/project/environment-client/\n- Workflow setup guide: `.github/workflows/README.md`\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 cogna-public\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.",
    "summary": "Python client for DEFRA's environment.data.gov.uk APIs (typed, async-friendly)",
    "version": "0.5.13",
    "project_urls": {
        "Bug Tracker": "https://github.com/cogna-public/environment-client/issues",
        "Homepage": "https://github.com/cogna-public/environment-client"
    },
    "split_keywords": [
        "api",
        " defra",
        " environment",
        " environment.data.gov.uk",
        " flood",
        " hydrology",
        " uk"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "c1ce53e5eb086e19a006226f2d14c988536e70cb4afb7a7ae7a122a3a4d8e068",
                "md5": "af55ba28977576891ff1ce2742515848",
                "sha256": "df9a7a3033fc07daf9ffc4c69acdf95365c9e5b1916693f15b58ef9c5569e300"
            },
            "downloads": -1,
            "filename": "environment_client-0.5.13-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "af55ba28977576891ff1ce2742515848",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 30069,
            "upload_time": "2025-10-09T11:34:29",
            "upload_time_iso_8601": "2025-10-09T11:34:29.849229Z",
            "url": "https://files.pythonhosted.org/packages/c1/ce/53e5eb086e19a006226f2d14c988536e70cb4afb7a7ae7a122a3a4d8e068/environment_client-0.5.13-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f96368faa5c6db988a73b20c3028ff1787db3d1e69ec17bd32f190cb5933ab3e",
                "md5": "83144b229daed6a80615ff6326acaac8",
                "sha256": "a5ba9cb2efaf9950daa51e0abb2dbfed3f66b90198491edf94e84ac63fe4d544"
            },
            "downloads": -1,
            "filename": "environment_client-0.5.13.tar.gz",
            "has_sig": false,
            "md5_digest": "83144b229daed6a80615ff6326acaac8",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 19651,
            "upload_time": "2025-10-09T11:34:31",
            "upload_time_iso_8601": "2025-10-09T11:34:31.029473Z",
            "url": "https://files.pythonhosted.org/packages/f9/63/68faa5c6db988a73b20c3028ff1787db3d1e69ec17bd32f190cb5933ab3e/environment_client-0.5.13.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-09 11:34:31",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "cogna-public",
    "github_project": "environment-client",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "environment-client"
}
        
Elapsed time: 1.43619s