eoapi-client 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ """Python client for eoAPI."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from ._http import EoApiConnectionError, EoApiError
6
+ from .api import EoApi
7
+ from .auth import TokenAuth, client_credentials_auth, mock_oidc_auth
8
+ from .raster import Raster
9
+ from .stac import AssetNotFoundError, Stac, UnsupportedAssetSchemeError
10
+ from .transactions import TransactionError, Transactions
11
+ from .vector import VectorTiles, open_features
12
+
13
+ __version__ = version("eoapi-client")
14
+
15
+ __all__ = [
16
+ "AssetNotFoundError",
17
+ "EoApi",
18
+ "EoApiConnectionError",
19
+ "EoApiError",
20
+ "Raster",
21
+ "Stac",
22
+ "TokenAuth",
23
+ "TransactionError",
24
+ "Transactions",
25
+ "UnsupportedAssetSchemeError",
26
+ "VectorTiles",
27
+ "__version__",
28
+ "client_credentials_auth",
29
+ "mock_oidc_auth",
30
+ "open_features",
31
+ ]
eoapi_client/_http.py ADDED
@@ -0,0 +1,114 @@
1
+ """Shared HTTP helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import version
6
+ from typing import Any, Self
7
+
8
+ import httpx
9
+
10
+ DEFAULT_TIMEOUT = 60.0
11
+
12
+
13
+ class EoApiError(Exception):
14
+ """An eoAPI HTTP request failed."""
15
+
16
+ def __init__(
17
+ self,
18
+ message: str,
19
+ *,
20
+ status_code: int | None = None,
21
+ url: str | None = None,
22
+ method: str | None = None,
23
+ body: str | None = None,
24
+ ) -> None:
25
+ self.status_code = status_code
26
+ self.url = url
27
+ self.method = method
28
+ self.body = body
29
+ super().__init__(message)
30
+
31
+
32
+ class EoApiConnectionError(EoApiError):
33
+ """An eoAPI request failed before a response was received (DNS, connection, timeout)."""
34
+
35
+
36
+ def raise_for_response(response: httpx.Response, error: type[EoApiError] = EoApiError) -> None:
37
+ if response.is_success:
38
+ return
39
+ response.read()
40
+ method, url = response.request.method, str(response.request.url)
41
+ raise error(
42
+ f"{method} {url} → {response.status_code}: {response.text[:500]}",
43
+ status_code=response.status_code,
44
+ url=url,
45
+ method=method,
46
+ body=response.text,
47
+ )
48
+
49
+
50
+ def new_client(timeout: float | httpx.Timeout = DEFAULT_TIMEOUT) -> httpx.Client:
51
+ """An `httpx.Client` with eoapi-client's defaults: redirects, connection retries, User-Agent."""
52
+ return httpx.Client(
53
+ timeout=timeout,
54
+ follow_redirects=True,
55
+ headers={"User-Agent": f"eoapi-client/{version('eoapi-client')}"},
56
+ transport=httpx.HTTPTransport(retries=2),
57
+ )
58
+
59
+
60
+ def request(
61
+ method: str,
62
+ url: str,
63
+ *,
64
+ client: httpx.Client | None = None,
65
+ error: type[EoApiError] = EoApiError,
66
+ **kwargs: Any,
67
+ ) -> httpx.Response:
68
+ try:
69
+ response = (client or httpx).request(method, url, **kwargs)
70
+ except httpx.TransportError as exc:
71
+ raise EoApiConnectionError(f"{method} {url} failed: {exc}", url=url, method=method) from exc
72
+ raise_for_response(response, error)
73
+ return response
74
+
75
+
76
+ class ClientOwner:
77
+ """Holds an `httpx.Client`, closing it on `close()` only if it created it."""
78
+
79
+ def __init__(self, client: httpx.Client | None, timeout: float) -> None:
80
+ self._client = client or new_client(timeout)
81
+ self._owns_client = client is None
82
+
83
+ def close(self) -> None:
84
+ if self._owns_client:
85
+ self._client.close()
86
+
87
+ def __enter__(self) -> Self:
88
+ return self
89
+
90
+ def __exit__(self, *exc: object) -> None:
91
+ self.close()
92
+
93
+
94
+ class Service(ClientOwner):
95
+ """Base for one eoAPI service. Headers and auth are sent per request, not as client defaults."""
96
+
97
+ def __init__(
98
+ self,
99
+ url: str,
100
+ *,
101
+ client: httpx.Client | None = None,
102
+ headers: dict[str, str] | None = None,
103
+ auth: httpx.Auth | None = None,
104
+ timeout: float = DEFAULT_TIMEOUT,
105
+ ) -> None:
106
+ super().__init__(client, timeout)
107
+ self._url = url.rstrip("/")
108
+ self._headers = headers or {}
109
+ self._auth = auth
110
+
111
+ def _request(self, method: str, path: str, *, error: type[EoApiError] = EoApiError, **kwargs: Any) -> httpx.Response:
112
+ headers = {**self._headers, **kwargs.pop("headers", {})}
113
+ url = f"{self._url}{path}"
114
+ return request(method, url, client=self._client, error=error, headers=headers, auth=self._auth, **kwargs)
eoapi_client/api.py ADDED
@@ -0,0 +1,61 @@
1
+ """`EoApi`: one entry point per eoAPI deployment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ import httpx
8
+
9
+ from eoapi_client._http import DEFAULT_TIMEOUT, ClientOwner
10
+ from eoapi_client.auth import TokenAuth
11
+ from eoapi_client.raster import Raster
12
+ from eoapi_client.stac import Stac
13
+ from eoapi_client.transactions import Transactions
14
+ from eoapi_client.vector import VectorTiles, open_features
15
+
16
+ if TYPE_CHECKING:
17
+ from owslib.ogcapi.features import Features
18
+
19
+
20
+ class EoApi(ClientOwner):
21
+ """All services of one eoAPI deployment, sharing one `httpx.Client`.
22
+
23
+ Service URLs default to eoapi-k8s's ingress paths under `base_url`
24
+ (`/stac`, `/raster`, `/vector`); pass `stac_url=` etc. to override any
25
+ of them with an absolute URL.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ base_url: str,
31
+ *,
32
+ headers: dict[str, str] | None = None,
33
+ auth: httpx.Auth | None = None,
34
+ timeout: float = DEFAULT_TIMEOUT,
35
+ client: httpx.Client | None = None,
36
+ stac_url: str | None = None,
37
+ raster_url: str | None = None,
38
+ vector_url: str | None = None,
39
+ ) -> None:
40
+ super().__init__(client, timeout)
41
+ base = base_url.rstrip("/")
42
+ self._headers = headers or {}
43
+ self._auth = auth
44
+ self._vector_url = vector_url or f"{base}/vector"
45
+ stac_url = stac_url or f"{base}/stac"
46
+ kwargs: dict[str, Any] = {"client": self._client, "headers": headers, "auth": auth}
47
+ self.stac = Stac(stac_url, **kwargs)
48
+ self.transactions = Transactions(stac_url, **kwargs)
49
+ self.raster = Raster(raster_url or f"{base}/raster", **kwargs)
50
+ self.vector_tiles = VectorTiles(self._vector_url, **kwargs)
51
+
52
+ def vector(self) -> Features:
53
+ """Open an OWSLib `Features` client (see `open_features`); it doesn't share this client.
54
+
55
+ OWSLib only takes static headers: a `TokenAuth`'s current token is
56
+ added now, so a long-lived `Features` object won't refresh it.
57
+ """
58
+ headers = dict(self._headers)
59
+ if isinstance(self._auth, TokenAuth):
60
+ headers["Authorization"] = f"Bearer {self._auth.token()}"
61
+ return open_features(self._vector_url, headers=headers)
eoapi_client/auth.py ADDED
@@ -0,0 +1,66 @@
1
+ """Bearer tokens that fetch, cache and refresh themselves.
2
+
3
+ Pass one as `auth=` to `EoApi` or a service. Services only send it to their
4
+ own URL, never to foreign asset hosts.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import json
11
+ import math
12
+ import time
13
+ from collections.abc import Callable, Generator
14
+
15
+ import httpx
16
+
17
+ from eoapi_client._http import request
18
+
19
+
20
+ def _jwt_exp(token: str) -> float:
21
+ """The JWT's `exp` claim, or `math.inf` for opaque tokens (then only a 401 triggers a refetch)."""
22
+ try:
23
+ payload = token.split(".")[1]
24
+ return float(json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))["exp"])
25
+ except (IndexError, KeyError, TypeError, ValueError):
26
+ return math.inf
27
+
28
+
29
+ class TokenAuth(httpx.Auth):
30
+ """Bearer token from `fetch()`, cached until 30s before its JWT `exp`; refetched once on a 401."""
31
+
32
+ requires_request_body = True # so a request can be replayed after a 401
33
+
34
+ def __init__(self, fetch: Callable[[], str]) -> None:
35
+ self._fetch = fetch
36
+ self._token: str | None = None
37
+ self._expires_at = 0.0
38
+
39
+ def token(self) -> str:
40
+ if self._token is None or time.time() >= self._expires_at - 30:
41
+ self._token = self._fetch()
42
+ self._expires_at = _jwt_exp(self._token)
43
+ return self._token
44
+
45
+ def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]:
46
+ request.headers["Authorization"] = f"Bearer {self.token()}"
47
+ response = yield request
48
+ if response.status_code == 401:
49
+ self._token = None
50
+ request.headers["Authorization"] = f"Bearer {self.token()}"
51
+ yield request
52
+
53
+
54
+ def client_credentials_auth(token_url: str, client_id: str, client_secret: str, *, scope: str | None = None) -> TokenAuth:
55
+ """OAuth2 client-credentials grant, e.g. Keycloak's `.../realms/<realm>/protocol/openid-connect/token`."""
56
+ data = {"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret}
57
+ if scope:
58
+ data["scope"] = scope
59
+ return TokenAuth(lambda: str(request("POST", token_url, data=data).json()["access_token"]))
60
+
61
+
62
+ def mock_oidc_auth(url: str, *, username: str = "eoapi-client", scopes: str = "openid") -> TokenAuth:
63
+ """Tokens from eoapi-k8s's mock OIDC server (alukach/mock-oidc-server). Testing only."""
64
+ data = {"username": username, "scopes": scopes}
65
+ headers = {"Accept": "application/json"}
66
+ return TokenAuth(lambda: str(request("POST", f"{url.rstrip('/')}/", data=data, headers=headers).json()["token"]))
eoapi_client/py.typed ADDED
File without changes
eoapi_client/raster.py ADDED
@@ -0,0 +1,101 @@
1
+ """Raster access via titiler-pgstac: search mosaics, collections and single items.
2
+
3
+ https://stac-utils.github.io/titiler-pgstac/
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ from eoapi_client._http import Service
13
+
14
+ DEFAULT_TILE_MATRIX_SET = "WebMercatorQuad"
15
+
16
+
17
+ def _image(response: httpx.Response) -> bytes | None:
18
+ """The image bytes, or `None` when titiler has no data there (204)."""
19
+ return None if response.status_code == 204 else response.content
20
+
21
+
22
+ def _size(width: int | None, height: int | None) -> str:
23
+ return f"/{width}x{height}" if width and height else ""
24
+
25
+
26
+ class _Target:
27
+ """titiler-pgstac endpoints shared by a registered search, a collection and an item.
28
+
29
+ Extra keyword arguments (`assets`, `expression`, `rescale`,
30
+ `colormap_name`, ...) are passed through as query parameters; lists
31
+ become repeated keys (`assets=["a", "b"]` → `assets=a&assets=b`).
32
+ """
33
+
34
+ def __init__(self, raster: Raster, prefix: str) -> None:
35
+ self._raster = raster
36
+ self._prefix = prefix
37
+
38
+ def _get(self, path: str, **params: Any) -> httpx.Response:
39
+ return self._raster._request("GET", f"{self._prefix}{path}", params=params)
40
+
41
+ def info(self, **params: Any) -> dict[str, Any]:
42
+ return dict(self._get("/info", **params).json())
43
+
44
+ def tilejson(self, *, tile_matrix_set: str = DEFAULT_TILE_MATRIX_SET, **params: Any) -> dict[str, Any]:
45
+ return dict(self._get(f"/{tile_matrix_set}/tilejson.json", **params).json())
46
+
47
+ def tile_url_template(self, *, tile_matrix_set: str = DEFAULT_TILE_MATRIX_SET, **params: Any) -> str:
48
+ """The `{z}/{x}/{y}` tile URL template, ready for a map viewer (Leaflet, MapLibre, ...)."""
49
+ return str(self.tilejson(tile_matrix_set=tile_matrix_set, **params)["tiles"][0])
50
+
51
+ def point(self, lon: float, lat: float, **params: Any) -> dict[str, Any]:
52
+ return dict(self._get(f"/point/{lon},{lat}", **params).json())
53
+
54
+ def statistics(self, feature: dict[str, Any] | None = None, **params: Any) -> dict[str, Any]:
55
+ """Statistics within a GeoJSON `feature` (POST), or of a whole item (GET, items only)."""
56
+ method = "GET" if feature is None else "POST"
57
+ return dict(self._raster._request(method, f"{self._prefix}/statistics", json=feature, params=params).json())
58
+
59
+ def bbox(
60
+ self,
61
+ bbox: tuple[float, float, float, float],
62
+ *,
63
+ format: str = "png",
64
+ width: int | None = None,
65
+ height: int | None = None,
66
+ **params: Any,
67
+ ) -> bytes | None:
68
+ """An image of `bbox` (minx, miny, maxx, maxy), or `None` if titiler returns no data (204)."""
69
+ minx, miny, maxx, maxy = bbox
70
+ return _image(self._get(f"/bbox/{minx},{miny},{maxx},{maxy}{_size(width, height)}.{format}", **params))
71
+
72
+
73
+ class _ItemTarget(_Target):
74
+ def preview(
75
+ self, *, format: str = "png", width: int | None = None, height: int | None = None, **params: Any
76
+ ) -> bytes | None:
77
+ """A preview image of the whole item (`max_size=` limits its size)."""
78
+ return _image(self._get(f"/preview{_size(width, height)}.{format}", **params))
79
+
80
+
81
+ class Raster(Service):
82
+ """titiler-pgstac: register searches as mosaics and query searches, collections or items."""
83
+
84
+ def search(self, search_id: str) -> _Target:
85
+ return _Target(self, f"/searches/{search_id}")
86
+
87
+ def collection(self, collection_id: str) -> _Target:
88
+ return _Target(self, f"/collections/{collection_id}")
89
+
90
+ def item(self, collection_id: str, item_id: str) -> _ItemTarget:
91
+ return _ItemTarget(self, f"/collections/{collection_id}/items/{item_id}")
92
+
93
+ def register_search(self, search_body: dict[str, Any]) -> str:
94
+ """Register a STAC search as a mosaic via `POST /searches/register`.
95
+
96
+ `search_body` is a STAC search filter (`collections`, `bbox`,
97
+ `datetime`, `query`/`filter`, ...), optionally with a nested
98
+ `metadata` key (`assets`, `minzoom`, `maxzoom`, `defaults`, ...).
99
+ Returns the mosaic's `search_id`, for `search(search_id)`.
100
+ """
101
+ return str(self._request("POST", "/searches/register", json=search_body).json()["id"])
eoapi_client/stac.py ADDED
@@ -0,0 +1,104 @@
1
+ """STAC reads: collections, items, asset downloads."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from pathlib import Path
7
+ from typing import Any
8
+ from urllib.parse import urlparse
9
+
10
+ import httpx
11
+
12
+ from eoapi_client._http import (
13
+ EoApiConnectionError,
14
+ EoApiError,
15
+ Service,
16
+ new_client,
17
+ raise_for_response,
18
+ request,
19
+ )
20
+
21
+
22
+ class AssetNotFoundError(EoApiError):
23
+ """The requested asset key doesn't exist on the item."""
24
+
25
+
26
+ class UnsupportedAssetSchemeError(EoApiError):
27
+ """The asset href uses a scheme that can't be fetched over HTTP."""
28
+
29
+
30
+ class Stac(Service):
31
+ """Read collections and items from a STAC API and download assets."""
32
+
33
+ def _pages(self, path: str, key: str, params: dict[str, Any] | None) -> Iterator[dict[str, Any]]:
34
+ """Yield `data[key]` entries across pages, following `rel="next"` links."""
35
+ url: str | None = f"{self._url}{path}"
36
+ seen: set[str] = set()
37
+ while url and url not in seen:
38
+ seen.add(url)
39
+ data = request("GET", url, client=self._client, headers=self._headers, auth=self._auth, params=params).json()
40
+ yield from data.get(key) or []
41
+ url = next((link["href"] for link in data.get("links") or [] if link.get("rel") == "next"), None)
42
+ params = None # the next href already carries them; `{}` would make httpx drop its query
43
+
44
+ def iter_collections(self, **params: Any) -> Iterator[dict[str, Any]]:
45
+ """Yield the raw collection objects of `.../collections`, across all pages.
46
+
47
+ Plain HTTP, so it tolerates collections that fail `pystac_client`'s
48
+ stricter validation (`matches_object_type`). Extra keyword arguments
49
+ (`limit`, `q`, `bbox`, `datetime`, `filter`, `sortby`, ...) are passed
50
+ through as query parameters; use `**{"filter-lang": ...}` for names
51
+ that aren't valid identifiers.
52
+ """
53
+ return self._pages("/collections", "collections", params)
54
+
55
+ def collections(self, **params: Any) -> list[dict[str, Any]]:
56
+ """`list(iter_collections(**params))`."""
57
+ return list(self.iter_collections(**params))
58
+
59
+ def iter_items(self, collection: str, **params: Any) -> Iterator[dict[str, Any]]:
60
+ """Yield a collection's items across all pages; params as for `iter_collections`."""
61
+ return self._pages(f"/collections/{collection}/items", "features", params)
62
+
63
+ def get_collection(self, collection_id: str) -> dict[str, Any]:
64
+ return dict(self._request("GET", f"/collections/{collection_id}").json())
65
+
66
+ def get_item(self, collection: str, item_id: str) -> dict[str, Any]:
67
+ return dict(self._request("GET", f"/collections/{collection}/items/{item_id}").json())
68
+
69
+ def download_asset(self, collection: str, item_id: str, asset_key: str, dest: Path) -> Path:
70
+ """Resolve an item's asset href and stream it to `dest`.
71
+
72
+ Auth headers are only sent to the asset href when it shares the STAC
73
+ API's host — asset hrefs commonly point at a different host (object
74
+ storage, a CDN) that shouldn't receive the STAC API's bearer token.
75
+ Foreign hosts are fetched with a separate plain client, so a shared
76
+ client's default headers don't leak either.
77
+ """
78
+ asset = (self.get_item(collection, item_id).get("assets") or {}).get(asset_key)
79
+ if asset is None:
80
+ raise AssetNotFoundError(f"Asset {asset_key!r} not found on item {item_id!r}")
81
+ href = str(asset["href"])
82
+ parsed_href = urlparse(href)
83
+ if parsed_href.scheme not in ("http", "https"):
84
+ raise UnsupportedAssetSchemeError(
85
+ f"Asset {asset_key!r} uses an unsupported scheme ({parsed_href.scheme!r}) — "
86
+ "likely only reachable from inside the platform (e.g. a shared filesystem "
87
+ "mount) and cannot be downloaded directly."
88
+ )
89
+ same_host = parsed_href.netloc == urlparse(self._url).netloc
90
+ client = self._client if same_host else new_client(self._client.timeout)
91
+ dest.parent.mkdir(parents=True, exist_ok=True)
92
+ try:
93
+ kwargs: dict[str, Any] = {"headers": self._headers, "auth": self._auth} if same_host else {}
94
+ with client.stream("GET", href, **kwargs) as response:
95
+ raise_for_response(response)
96
+ with dest.open("wb") as f:
97
+ for chunk in response.iter_bytes():
98
+ f.write(chunk)
99
+ except httpx.TransportError as exc:
100
+ raise EoApiConnectionError(f"GET {href} failed: {exc}", url=href, method="GET") from exc
101
+ finally:
102
+ if not same_host:
103
+ client.close()
104
+ return dest
@@ -0,0 +1,90 @@
1
+ """STAC API Transactions extension client (item and collection writes).
2
+
3
+ https://github.com/stac-api-extensions/transaction
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from collections.abc import Iterable
10
+ from itertools import islice
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import urlparse
14
+
15
+ from eoapi_client._http import DEFAULT_TIMEOUT, EoApiError, Service, request
16
+
17
+ MERGE_PATCH = {"Content-Type": "application/merge-patch+json"}
18
+
19
+
20
+ class TransactionError(EoApiError):
21
+ """A STAC API Transactions request failed."""
22
+
23
+
24
+ def _as_json(obj: Any) -> dict[str, Any]:
25
+ """A dict as-is, a pystac object via `.to_dict()`, an `http(s)://` URL (fetched without auth), or a local path."""
26
+ if isinstance(obj, dict):
27
+ return obj
28
+ if hasattr(obj, "to_dict"):
29
+ return dict(obj.to_dict())
30
+ if urlparse(str(obj)).scheme in ("http", "https"):
31
+ return dict(request("GET", str(obj), timeout=DEFAULT_TIMEOUT).json())
32
+ return dict(json.loads(Path(obj).read_text()))
33
+
34
+
35
+ class Transactions(Service):
36
+ """Create, update and delete STAC items and collections via the Transactions extension.
37
+
38
+ Items and collections may be given as a dict, a pystac object, a local
39
+ file path or an `http(s)://` URL.
40
+ """
41
+
42
+ def _write(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]:
43
+ return dict(self._request(method, path, error=TransactionError, **kwargs).json())
44
+
45
+ def add_item(self, collection: str, item: Any) -> dict[str, Any]:
46
+ """Create an item via `POST /collections/{collection}/items`."""
47
+ return self._write("POST", f"/collections/{collection}/items", json=_as_json(item))
48
+
49
+ def update_item(self, collection: str, item: Any) -> dict[str, Any]:
50
+ """Replace an item via `PUT /collections/{collection}/items/{item["id"]}`."""
51
+ body = _as_json(item)
52
+ return self._write("PUT", f"/collections/{collection}/items/{body['id']}", json=body)
53
+
54
+ def patch_item(self, collection: str, item_id: str, patch: dict[str, Any]) -> dict[str, Any]:
55
+ """Update an item with a JSON merge patch (RFC 7396)."""
56
+ path = f"/collections/{collection}/items/{item_id}"
57
+ return self._write("PATCH", path, content=json.dumps(patch), headers=MERGE_PATCH)
58
+
59
+ def delete_item(self, collection: str, item_id: str) -> None:
60
+ """Delete an item via `DELETE .../items/{item_id}`."""
61
+ self._request("DELETE", f"/collections/{collection}/items/{item_id}", error=TransactionError)
62
+
63
+ def bulk_add_items(
64
+ self, collection: str, items: Iterable[Any], *, method: str = "insert", chunk_size: int = 500
65
+ ) -> None:
66
+ """Insert (or, with `method="upsert"`, upsert) items via `POST .../bulk_items`, `chunk_size` per request.
67
+
68
+ Each chunk is its own request: if one fails, earlier chunks stay committed.
69
+ """
70
+ it = iter(items)
71
+ while chunk := [_as_json(item) for item in islice(it, chunk_size)]:
72
+ body = {"items": {item["id"]: item for item in chunk}, "method": method}
73
+ self._request("POST", f"/collections/{collection}/bulk_items", error=TransactionError, json=body)
74
+
75
+ def add_collection(self, collection: Any) -> dict[str, Any]:
76
+ """Create a collection via `POST /collections`."""
77
+ return self._write("POST", "/collections", json=_as_json(collection))
78
+
79
+ def update_collection(self, collection: Any) -> dict[str, Any]:
80
+ """Replace a collection via `PUT /collections/{collection["id"]}`."""
81
+ body = _as_json(collection)
82
+ return self._write("PUT", f"/collections/{body['id']}", json=body)
83
+
84
+ def patch_collection(self, collection_id: str, patch: dict[str, Any]) -> dict[str, Any]:
85
+ """Update a collection with a JSON merge patch (RFC 7396)."""
86
+ return self._write("PATCH", f"/collections/{collection_id}", content=json.dumps(patch), headers=MERGE_PATCH)
87
+
88
+ def delete_collection(self, collection_id: str) -> None:
89
+ """Delete a collection via `DELETE /collections/{collection_id}` (pgstac also deletes its items)."""
90
+ self._request("DELETE", f"/collections/{collection_id}", error=TransactionError)
eoapi_client/vector.py ADDED
@@ -0,0 +1,74 @@
1
+ """Vector access via tipg: features through OWSLib, vector tiles through `VectorTiles`.
2
+
3
+ tipg implements OGC API - Features, including Part 3 (Filtering / CQL2),
4
+ which `owslib.ogcapi.features.Features` already covers well: header
5
+ passthrough (for auth) and `filter`/`filter-lang` are both plain
6
+ pass-through query parameters, so there is nothing tipg-specific left to
7
+ reimplement. `open_features` only wires eoAPI's URL/header conventions into
8
+ OWSLib, and requires the optional `owslib` dependency:
9
+ `pip install eoapi-client[vector]`. OWSLib doesn't cover tipg's vector
10
+ tiles (MVT), which `VectorTiles` does.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ import httpx
18
+
19
+ from eoapi_client._http import Service
20
+ from eoapi_client.raster import DEFAULT_TILE_MATRIX_SET
21
+
22
+ if TYPE_CHECKING:
23
+ from owslib.ogcapi.features import Features
24
+
25
+
26
+ def open_features(vector_url: str, *, headers: dict[str, str] | None = None) -> Features:
27
+ """Open an OWSLib `Features` client against a tipg deployment.
28
+
29
+ `Features` fetches the landing page immediately on construction, so
30
+ `vector_url` must be reachable when this is called. See
31
+ https://owslib.readthedocs.io/en/latest/usage.html#ogc-api-features for
32
+ the full client API (`collections()`, `collection_items()`,
33
+ `collection_item()`, CQL2 filtering via `filter`/`filter-lang`, ...).
34
+
35
+ Non-2xx responses raise a plain `RuntimeError` — OWSLib doesn't expose
36
+ the response's status code.
37
+ """
38
+ try:
39
+ from owslib.ogcapi.features import Features
40
+ except ImportError as exc: # pragma: no cover
41
+ raise ImportError("owslib is required for vector access — install eoapi-client[vector]") from exc
42
+ return Features(vector_url, headers=headers)
43
+
44
+
45
+ class VectorTiles(Service):
46
+ """tipg vector tiles (MVT) for a collection: a PostGIS table or function, e.g. `public.my_data`.
47
+
48
+ Extra keyword arguments (`limit`, `columns`, `filter`, `geom-column`, ...)
49
+ are passed through as query parameters.
50
+ """
51
+
52
+ def _get(self, collection_id: str, tile_matrix_set: str, path: str, params: dict[str, Any]) -> httpx.Response:
53
+ return self._request("GET", f"/collections/{collection_id}/tiles/{tile_matrix_set}/{path}", params=params)
54
+
55
+ def tilejson(
56
+ self, collection_id: str, *, tile_matrix_set: str = DEFAULT_TILE_MATRIX_SET, **params: Any
57
+ ) -> dict[str, Any]:
58
+ return dict(self._get(collection_id, tile_matrix_set, "tilejson.json", params).json())
59
+
60
+ def tile_url_template(self, collection_id: str, *, tile_matrix_set: str = DEFAULT_TILE_MATRIX_SET, **params: Any) -> str:
61
+ """The `{z}/{x}/{y}` tile URL template, ready for a map viewer (MapLibre, ...)."""
62
+ return str(self.tilejson(collection_id, tile_matrix_set=tile_matrix_set, **params)["tiles"][0])
63
+
64
+ def style_json(
65
+ self, collection_id: str, *, tile_matrix_set: str = DEFAULT_TILE_MATRIX_SET, **params: Any
66
+ ) -> dict[str, Any]:
67
+ """A MapLibre style for the collection's tiles."""
68
+ return dict(self._get(collection_id, tile_matrix_set, "style.json", params).json())
69
+
70
+ def tile(
71
+ self, collection_id: str, z: int, x: int, y: int, *, tile_matrix_set: str = DEFAULT_TILE_MATRIX_SET, **params: Any
72
+ ) -> bytes:
73
+ """One MVT tile; tipg returns empty bytes where there are no features."""
74
+ return bytes(self._get(collection_id, tile_matrix_set, f"{z}/{x}/{y}", params).content)
@@ -0,0 +1,228 @@
1
+ Metadata-Version: 2.4
2
+ Name: eoapi-client
3
+ Version: 0.1.0
4
+ Summary: Python client for eoAPI
5
+ Keywords: eoapi,stac,titiler,tipg,geospatial,earth-observation
6
+ Author: Development Seed
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Scientific/Engineering :: GIS
17
+ Classifier: Typing :: Typed
18
+ Requires-Dist: httpx>=0.28.0
19
+ Requires-Dist: owslib>=0.30 ; extra == 'vector'
20
+ Requires-Python: >=3.11
21
+ Project-URL: Homepage, https://github.com/developmentseed/eoapi-client
22
+ Project-URL: Repository, https://github.com/developmentseed/eoapi-client
23
+ Project-URL: Issues, https://github.com/developmentseed/eoapi-client/issues
24
+ Project-URL: Changelog, https://github.com/developmentseed/eoapi-client/blob/main/CHANGELOG.md
25
+ Provides-Extra: vector
26
+ Description-Content-Type: text/markdown
27
+
28
+ # eoapi-client
29
+
30
+ Python client for [eoAPI](https://eoapi.dev).
31
+
32
+ > [!WARNING]
33
+ > This project is in early development. The API is not stable yet.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ uv add eoapi-client
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ `EoApi` bundles all services of one deployment behind one shared HTTP
44
+ client (connection reuse, redirects, connection retries):
45
+
46
+ ```python
47
+ from pathlib import Path
48
+ from eoapi_client import EoApi
49
+
50
+ with EoApi("https://example.com", headers={"Authorization": "Bearer ..."}) as api:
51
+ api.stac.collections(q="sentinel") # all pages; search params pass through
52
+ for item in api.stac.iter_items("my-collection", datetime="2024-01-01T00:00:00Z/.."):
53
+ ...
54
+ api.stac.get_item("my-collection", "item-1")
55
+ api.stac.download_asset("my-collection", "item-1", "data", Path("./data.tif"))
56
+ api.transactions.add_item("my-collection", "./item.geojson")
57
+ api.raster.search(api.raster.register_search({"collections": ["my-collection"]})).tile_url_template()
58
+ api.vector().collections()
59
+ ```
60
+
61
+ Service URLs default to eoapi-k8s's ingress paths (`/stac`, `/raster`,
62
+ `/vector`) under the base URL; override any with `stac_url=`, `raster_url=`
63
+ or `vector_url=`. Pass `client=` to use your own `httpx.Client`, and
64
+ `timeout=` (default 60s) otherwise.
65
+
66
+ Each service also works on its own, as shown below. `Stac`, `Transactions`,
67
+ `Raster` and `VectorTiles` take
68
+ `(url, *, headers=None, auth=None, client=None, timeout=60.0)`.
69
+
70
+ Write STAC items and collections via the [Transactions
71
+ extension](https://github.com/stac-api-extensions/transaction). Items and
72
+ collections can be a dict, a pystac object, a local path or a URL:
73
+
74
+ ```python
75
+ from eoapi_client import Transactions
76
+
77
+ tx = Transactions("https://example.com/stac", headers={"Authorization": "Bearer ..."})
78
+ created = tx.add_item("my-collection", "./item.geojson")
79
+ tx.patch_item("my-collection", created["id"], {"properties": {"title": "New"}}) # JSON merge patch
80
+ tx.bulk_add_items("my-collection", items, method="upsert") # chunked, 500 per request
81
+ tx.delete_item("my-collection", created["id"])
82
+ ```
83
+
84
+ Items: `add_item`, `update_item` (PUT), `patch_item`, `delete_item`,
85
+ `bulk_add_items`. Collections: `add_collection`, `update_collection`,
86
+ `patch_collection`, `delete_collection` (pgstac also deletes the
87
+ collection's items).
88
+
89
+ List STAC collections (plain HTTP, so it tolerates collections that fail
90
+ `pystac_client`'s stricter validation) and download an item's asset:
91
+
92
+ ```python
93
+ from pathlib import Path
94
+ from eoapi_client import Stac
95
+
96
+ with Stac("https://example.com/stac", headers={"Authorization": "Bearer ..."}) as stac:
97
+ collections = stac.collections()
98
+ stac.download_asset("my-collection", "item-1", "data", Path("./data.tif"))
99
+ ```
100
+
101
+ `download_asset` only forwards the given headers to the asset href when it
102
+ shares the STAC API's host — asset hrefs often point elsewhere (object
103
+ storage, a CDN) that shouldn't receive the STAC API's bearer token.
104
+
105
+ Turn a STAC search into map tiles via
106
+ [titiler-pgstac](https://stac-utils.github.io/titiler-pgstac/)'s mosaic
107
+ endpoints:
108
+
109
+ ```python
110
+ from eoapi_client import Raster
111
+
112
+ raster = Raster("https://example.com/raster", headers={"Authorization": "Bearer ..."})
113
+ search_id = raster.register_search({"collections": ["my-collection"]})
114
+ tile_url = raster.search(search_id).tile_url_template(assets="data")
115
+ # -> "https://example.com/raster/searches/<id>/tiles/WebMercatorQuad/{z}/{x}/{y}?assets=data"
116
+ ```
117
+
118
+ Extra keyword arguments (`assets`, `expression`, `rescale`,
119
+ `colormap_name`, ...) are forwarded as query parameters to titiler, and lists
120
+ become repeated keys. Use `raster.collection(collection_id)` instead of
121
+ `raster.search(search_id)` when you want a whole collection's mosaic without
122
+ registering a search first.
123
+
124
+ For analysis, `raster.item(collection_id, item_id)`,
125
+ `raster.collection(collection_id)` and `raster.search(search_id)` share
126
+ `info`, `tilejson`, `tile_url_template`, `point`, `statistics` and `bbox`.
127
+ Items also have `preview`:
128
+
129
+ ```python
130
+ item = raster.item("my-collection", "item-1")
131
+ item.info(assets="data")
132
+ png = item.preview(assets="data", max_size=512) # bytes
133
+ item.point(-86.39, 36.21, assets="data")["values"]
134
+ item.statistics(assets="data") # whole item
135
+ raster.collection("my-collection").statistics(feature, assets="data", max_size=512) # within a GeoJSON feature
136
+ ```
137
+
138
+ Image methods return `None` when titiler has no data there (HTTP 204).
139
+
140
+ Query vector collections (tipg's OGC API - Features) via
141
+ [OWSLib](https://owslib.readthedocs.io/en/latest/usage.html#ogc-api-features)
142
+ — tipg's `/collections`, `/collections/{id}/items`, and CQL2 filtering are
143
+ already well covered there, so this only wires up eoAPI's URL/header
144
+ conventions instead of reimplementing a features client. Requires the
145
+ `vector` extra: `uv add eoapi-client[vector]`.
146
+
147
+ ```python
148
+ from eoapi_client import open_features
149
+
150
+ features = open_features("https://example.com/vector", headers={"Authorization": "Bearer ..."})
151
+ collections = features.collections()
152
+ items = features.collection_items("my-collection", **{"filter": "ogc_fid = 3", "filter-lang": "cql2-text"})
153
+ ```
154
+
155
+ `open_features()` returns a plain `owslib.ogcapi.features.Features` — see
156
+ its docs for the full API (`collection_item()`, `collection_queryables()`,
157
+ item writes, ...). OWSLib raises its own errors; see [Errors](#errors).
158
+
159
+ tipg's vector tiles (MVT), which OWSLib doesn't cover, come from
160
+ `VectorTiles` (or `api.vector_tiles`), with no extra needed:
161
+
162
+ ```python
163
+ from eoapi_client import VectorTiles
164
+
165
+ vt = VectorTiles("https://example.com/vector")
166
+ vt.tile_url_template("public.my_data") # for a MapLibre vector source
167
+ vt.style_json("public.my_data") # a ready-made MapLibre style
168
+ vt.tile("public.my_data", 0, 0, 0) # MVT bytes; empty where there are no features
169
+ ```
170
+
171
+ ## Auth
172
+
173
+ Pass `auth=` to `EoApi` (or any service) to have tokens fetched, cached
174
+ until shortly before they expire, and refetched once on a 401:
175
+
176
+ ```python
177
+ from eoapi_client import EoApi, client_credentials_auth, mock_oidc_auth
178
+
179
+ # Keycloak (or any OAuth2 client-credentials token endpoint)
180
+ auth = client_credentials_auth(
181
+ "https://keycloak.example.com/realms/eoapi/protocol/openid-connect/token",
182
+ client_id="ingest",
183
+ client_secret="...",
184
+ )
185
+ # eoapi-k8s's mock OIDC server, for testing
186
+ auth = mock_oidc_auth("http://localhost/mock-oidc")
187
+
188
+ api = EoApi("https://example.com", auth=auth)
189
+ ```
190
+
191
+ `TokenAuth(fetch)` wraps any other token source: `fetch()` returns a token
192
+ string, and its expiry is read from the JWT's `exp` claim. For a static token,
193
+ keep using `headers={"Authorization": "Bearer ..."}`. Tokens are only sent to
194
+ the configured service URLs, never to asset hosts elsewhere. `api.vector()`
195
+ gets the token current at call time, because OWSLib only takes static headers.
196
+
197
+ ## Errors
198
+
199
+ Every failure raised by eoapi-client is an `EoApiError`:
200
+
201
+ - `EoApiError`: HTTP failure, with `status_code`, `url`, `method` and `body`
202
+ (the response text).
203
+ - `EoApiConnectionError`: no response (DNS, connection refused, timeout).
204
+ - `TransactionError`: a Transactions request failed.
205
+ - `AssetNotFoundError` / `UnsupportedAssetSchemeError`: from `Stac.download_asset`.
206
+
207
+ The exception is `open_features()`: OWSLib raises a plain `RuntimeError` on
208
+ non-2xx responses, with no status code attached.
209
+
210
+ ## Development
211
+
212
+ ```bash
213
+ uv sync
214
+ uv run pytest
215
+ uv run pre-commit install
216
+ ```
217
+
218
+ Integration tests run against a live
219
+ [eoapi-k8s](https://github.com/developmentseed/eoapi-k8s) deployment (with its
220
+ mock OIDC server and sample data) and are skipped unless `EOAPI_URL` is set:
221
+
222
+ ```bash
223
+ EOAPI_URL=http://localhost uv run pytest tests/integration
224
+ ```
225
+
226
+ ## License
227
+
228
+ [MIT](LICENSE)
@@ -0,0 +1,13 @@
1
+ eoapi_client/__init__.py,sha256=SmiyXf7xLj_QWEwuF-qqOIs1tG84Le0u3N7O_nYHwFY,792
2
+ eoapi_client/_http.py,sha256=NumiyZG__lihi5MPXPWihPbLXQLJT5RERVea3IzkhP8,3389
3
+ eoapi_client/api.py,sha256=5X4WKUj9W-W600L9YAht5eWk_w9JJFasVn-BjfKqz2Q,2246
4
+ eoapi_client/auth.py,sha256=yCRN9muv7aVt9-YVQhHUAQSUG3IERoiD5NHctpMwDSw,2592
5
+ eoapi_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ eoapi_client/raster.py,sha256=oQnQldTj0dLvxLeoCIjGJzC7ANuY8A5b_ZFx6qqgJ7k,4183
7
+ eoapi_client/stac.py,sha256=zhXOnTeXaF7tTXzOua7YqPsTkwSVK7WdzVG6wqCxDmU,4726
8
+ eoapi_client/transactions.py,sha256=ourscMUM9eXQn-LUitfeMEKXbZ2c-D-EXma7yLpSulQ,4150
9
+ eoapi_client/vector.py,sha256=Xv8n8AVCqzWiBeORjIy1jPW-qtWAvAi7XM2lg0hGW7U,3440
10
+ eoapi_client-0.1.0.dist-info/licenses/LICENSE,sha256=VRb2Bx0c2u6mtWwU_cBiJx_5qrDwzkG3YMZfV0FQnhU,1073
11
+ eoapi_client-0.1.0.dist-info/WHEEL,sha256=3OmCxFA0ffBIsX4x0o8CdfSvZAOvO3mzEG8U_z5TvV4,80
12
+ eoapi_client-0.1.0.dist-info/METADATA,sha256=srcynKbOMQm13xj-RP4RBer7poipX7koIuBvtOCOlOI,8732
13
+ eoapi_client-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.8
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Development Seed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.