Metadata-Version: 2.5
Name: georest
Version: 0.6.1
Summary: Python clients for public geospatial REST APIs: ArcGIS Image, Map and Feature Services and Portal search; the USFS Enterprise Data Warehouse, FIA estimates and LCMS summaries; USGS water, river network, elevation, earthquake, ScienceBase and water-quality services; FEMA flood maps and disaster declarations; and NOAA weather, river, tide and hurricane services.
Project-URL: Homepage, https://georest.io
Project-URL: Repository, https://github.com/redcastle-resources/georest
Project-URL: Issues, https://github.com/redcastle-resources/georest/issues
Project-URL: Changelog, https://github.com/redcastle-resources/georest/blob/main/CHANGELOG.md
Project-URL: Documentation, https://georest.io
Author: Ryan Rock, Ian Housman
Maintainer-email: RedCastle Resources <ryan.rock@redcastleresources.com>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: 3dep,agol,arcgis,disasters,earthquakes,edw,elevation,esri,evalidator,feature-service,fema,fia,flood,forest-inventory,forest-service,geojson,geospatial,gis,hurricanes,hydrology,image-service,land-cover,lcms,map-service,mcp,nfhl,nldi,noaa,nwis,nws,ogc-api,ogc-api-features,portal,rest,sciencebase,streamflow,tides,usfs,usgs,water-data,water-quality,weather
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: pandas>=1.5
Provides-Extra: dev
Requires-Dist: build>=1.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: twine>=6.1; extra == 'dev'
Provides-Extra: ee
Requires-Dist: earthengine-api>=1.0; extra == 'ee'
Provides-Extra: examples
Requires-Dist: ipython>=8.0; extra == 'examples'
Requires-Dist: jupyterlab>=4.0; extra == 'examples'
Requires-Dist: plotly>=5.0; extra == 'examples'
Provides-Extra: mcp
Requires-Dist: mcp<2,>=1.2; extra == 'mcp'
Description-Content-Type: text/markdown

# georest

Python clients for geospatial REST APIs: ArcGIS Image, Map and Feature Services, ArcGIS
Portal search, the USFS Enterprise Data Warehouse (EDW), Forest Service FIA estimates and
LCMS summaries, and the USGS Water Data OGC API.

**One dependency: pandas**, used by the USGS and Forest Service clients, which return
DataFrames. The Esri clients use only the standard library. Earth Engine is optional, for
summarizing LCMS over your own polygon.

```bash
pip install georest
pip install "georest[ee]"      # adds Earth Engine for usfs.lcms_ee
pip install "georest[mcp]"     # adds georest-mcp, the MCP server for LLM agents
```

Documentation: **[georest.io](https://georest.io)**.

## Quick start

```python
from georest.esri import portal, services
from georest.usfs import edw

# Search the USFS EDW catalog by keyword or theme
hits = edw.search_edw_services("fire")

# Pull features as GeoJSON (layer 63 = "Burned Area Boundaries (All Years)")
geojson = edw.query_features(
    "EDW_MTBS_01", 63,
    where="fire_name LIKE '%CAMERON PEAK%'",
    out_fields="fire_name,acres,year",
)

# Search any ArcGIS Portal - IIPP, ArcGIS Online, USGS, NOAA, USFS, NASA,
# or any ArcGIS Enterprise install
results = portal.searchPortal("naip 2023", portal="agol")

# Generic ArcGIS service operations, on any layer (EDW's queries are these)
tile_url = services.getImageServiceTileUrl("https://.../ImageServer")
fires = services.queryFeatureService(edw.layer_url("EDW_MTBS_01", 62),
                                     max_features=5000, if_more="page")

# USGS Water Data: find gages in a box, pull a month of daily discharge
from georest.usgs import waterdata

gages = waterdata.search_monitoring_locations(bbox=(-111.7, 36.8, -111.5, 37.0),
                                              site_type_code="ST")
flow = waterdata.get_daily_values("USGS-09380000", "00060",
                                  start="2024-01-01", end="2024-01-31")
flow[["time", "value"]]   # a DataFrame, value as a number

# Forest Service: FIA estimates always come with their sampling error
from georest.usfs import fia, lcms

fia.find_attributes("carbon")                      # what can be estimated
wc = fia.find_evaluations("Oregon")["wc"].iloc[0]  # which inventory
df = fia.estimate(wc, 2, rselected="County code and name")   # se_pct, plots, unreliable
lcms.lcms_summary("Land_Cover", state="Oregon", county="Crook")
```

The provider modules are also re-exported at the top level, so `from georest import edw`
and `from georest import waterdata` work too. They load lazily, so `import georest` costs
almost nothing.

## Maps

`georest.view` draws ArcGIS services, GeoJSON and XYZ tiles on an interactive
map, with query, legends, time lapses and area charts. `Map.addLayer` works out
what it was given: an ArcGIS feature layer, map service or image service URL, a
tile URL with `{z}`, `{x}` and `{y}`, or GeoJSON (a URL, text or a dict).

```python
from georest.view import Map

Map.addLayer("https://hazards.fema.gov/arcgis/rest/services/public/NFHL/MapServer",
             {"layers": "show:28"}, "Flood hazard")
Map.addLayer("https://services3.arcgis.com/T4QMspbfLg3qTGWY/arcgis/rest/services/"
             "WFIGS_Interagency_Perimeters_Current/FeatureServer/0", {}, "Fire perimeters")
# an image service: every scene in a window, combined per pixel by a reducer
Map.addLayer("https://landsat2.arcgis.com/arcgis/rest/services/Landsat/MS/ImageServer",
             {"time": ("2020-06-01", "2020-09-30"), "reducer": "min"}, "Landsat summer 2020")
# tiles: Query shows the color under the click, named by classLegendDict
Map.addLayer("https://basemap.nationalmap.gov/arcgis/rest/services/USGSHydroCached/MapServer/tile/{z}/{y}/{x}",
             {"classLegendDict": {"Water body": "cbe6ff"}}, "Hydrography")
Map.addLayer("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojson", {}, "Earthquakes")
Map.setCenter(-105.1, 40.6, 9)
Map.turnOnInspector()
Map.view()                       # or Map.export_html("map.html")
```

For a time-enabled image or map service shown as a time lapse, one frame per
time step, use `Map.addTimeLapse(url, viz, name)`. `examples/view_example.py`
shows every kind of input.

## Layout

| Import path | What it covers |
|---|---|
| `georest.esri.portal` | ArcGIS Portal search and service metadata |
| `georest.esri.services` | Generic Image/Map/Feature Service queries (one request, or paged past the server's limit), window-function analytics, and raster operations |
| `georest.usgs.waterdata` | USGS Water Data OGC API: monitoring locations, daily/continuous values, field measurements, peaks, time-series metadata |
| `georest.usfs` | Forest Service FIA estimates (EVALIDator) with sampling errors, LCMS land cover/use/change summaries, and the two side by side |
| `georest.usfs.edw` | The Forest Service Enterprise Data Warehouse (EDW): catalog search, layer-role tagging, FGDC/ISO metadata, and feature and analytic queries through `georest.esri.services`. It was `georest.esri.edw` until 0.5.2; that name still works, with a deprecation warning |
| `georest.fema.nfhl` | FEMA's National Flood Hazard Layer: the flood zone at a point, when that map took effect, and new maps that are pending or preliminary |
| `georest.fema.openfema` | OpenFEMA disaster declarations: by declared county, or one row per disaster |
| `georest.noaa` | NWS alerts, forecasts and observations (one unit system per call), NWPS river gauges with flood stages, CO-OPS tides, NHC active storms |

`esri` is the Esri/ArcGIS provider, `usgs` the USGS provider, `usfs` the
USDA Forest Service provider, `fema` the FEMA provider, and `noaa` the NOAA
provider. Each sits under
`georest` as a subpackage so providers can be added alongside one another without a
namespace collision, and each is self-contained - its private `_http` (and, for
usgs, `_ogc`) module is its own.

Full per-function reference: **[docs/api.md](docs/api.md)**.
Runnable notebooks: **[examples/](examples/)**. The `guide_*` notebooks each answer one question
with interactive charts and maps; the others walk through one module function by function.

## An MCP server for LLM agents

`georest-mcp` serves georest's data clients as Model Context Protocol tools over stdio:
FIA estimates and LCMS summaries, USGS water data, the river network, elevation,
earthquakes, ScienceBase and water quality, and EDW, portal and Feature Service queries. It
has 18 read-only tools and no code execution. Register it with your client, e.g. for Claude Code:

```json
{"mcpServers": {"georest": {"command": "georest-mcp"}}}
```

See [docs/api.md](docs/api.md#using-georest-from-an-mcp-server) for what the tools return
and the rules they follow.

## Signing in to ArcGIS Online / Portal

Public services need no sign-in. For secured content, sign in once and every `portal` and
`services` call without an explicit `token=` uses your session, sent only to the portal's
own hosts (never to, say, a public NOAA service).

One-time setup, per AGOL org or Enterprise portal:

1. Content > New item > Developer credentials > **OAuth 2.0 credentials**.
2. Add the redirect URL `http://127.0.0.1:8765/callback`.
3. Note the **client id**. No client secret is needed.

Then pick whichever fits:

```python
from georest.esri import auth

# Notebook or script: browser sign-in; enterprise SSO (SAML/eAuth) works.
auth.login("https://myorg.maps.arcgis.com", client_id="abc123")

# ArcGIS Pro: reuse Pro's session via the arcgis API (run in Pro's Python).
from arcgis.gis import GIS
gis = GIS("Pro")
auth.set_token(gis._con.token, portal=gis.url, refresh=lambda: gis._con.token)

auth.status()   # who you are and until when; never the token
```

For an MCP server or any long-running process, sign in from a terminal once:

```bash
georest-login --portal https://myorg.maps.arcgis.com --client-id abc123
```

That saves a refresh token to `~/.georest/esri_credentials.json`; later processes pick it
up automatically until the refresh token expires (two weeks by default, set by your org),
then run the command again. `georest-login --logout` removes it. `GEOREST_ESRI_PORTAL` and
`GEOREST_ESRI_CLIENT_ID` can stand in for the flags.

## USGS API key

The Water Data API works anonymously, rate-limited to "a few queries per hour". For more,
[get a free key](https://api.waterdata.usgs.gov/signup/) and set `USGS_API_KEY` in the
environment (or call `waterdata.set_api_key(...)` once at startup). The key is sent only as
the `X-Api-Key` header - never in a URL, so it cannot leak through an error message or a
log line. Every result carries the remaining budget when the server reports it
(`fc["rate_limit"]`), and a 429 the server won't let the client wait out raises
`waterdata.RateLimitError` with a `.retry_after` rather than blocking.

## Maintenance tool

```bash
georest-check-themes          # report drift vs. the live EDW catalog
georest-check-themes --emit   # + paste-ready _SERVICE_THEMES entries
```

`georest.usfs.edw._SERVICE_THEMES` is hand-curated and powers theme filtering and description
matching. EDW publishes and retires services without notice, so the table rots
quietly - an untyped service still appears in search results, but as theme
`uncategorized` with no description for keyword matching to reach. Exit status is
0 in sync, 1 drifted, 2 unreachable.

## Migrating from RESTesri

This package was previously a loose `RESTesri/` directory that worked only when the
repository root happened to be on `sys.path`. Update imports:

```python
from RESTesri import edw                    # before
from georest.usfs import edw            # after

from RESTesri._http import fetch_json       # before
from georest.esri._http import fetch_json   # after
```

Then delete any `sys.path.insert(...)` bootstrap - `pip install georest` (or
`pip install -e .` from a clone) makes it unnecessary.

## Development

```bash
git clone https://github.com/redcastle-resources/georest
cd georest
pip install -e ".[dev]"

python -m pytest                              # or: python -m unittest discover -s tests -t .
EDW_LIVE=1 SERVICES_LIVE=1 USGS_LIVE=1 python -m pytest   # include the network tests
```

This is a `src/` layout, so `pip install -e .` is required before the tests can
import the package - that is deliberate. It makes the suite import the installed
artifact rather than the source directory, so a packaging mistake fails loudly
instead of being masked by the working directory.

Live tests skip rather than fail when the servers are unreachable; EDW
intermittently answers 404, 500, `Layer not found`, or 200-with-no-layers for
services that work moments later, and the USGS API rate-limits anonymous callers.
See [tests/README.md](tests/README.md) and [CONTRIBUTING.md](CONTRIBUTING.md).

## Requirements

Python 3.9 or newer, and pandas 1.5 or newer. The 3.9 floor is deliberate: ArcGIS Pro
3.0–3.2 ships Python 3.9 (with pandas), and that is squarely this library's audience.

## License

Apache License 2.0 - see [LICENSE](LICENSE).

`portal.py` and `services.py` were ported from
[geeViz](https://github.com/gee-community/geeViz)'s `esriLib.py`, with the
viewer-rendering functions removed; these modules fetch data rather than render it.
