stac-api-protocol 0.1.0__tar.gz → 0.1.1__tar.gz

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.
Files changed (39) hide show
  1. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/CHANGELOG.md +5 -4
  2. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/PKG-INFO +6 -1
  3. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/README.md +5 -0
  4. stac_api_protocol-0.1.1/demo/.gitignore +1 -0
  5. stac_api_protocol-0.1.1/demo/README.md +50 -0
  6. stac_api_protocol-0.1.1/demo/download-data.sh +24 -0
  7. stac_api_protocol-0.1.1/demo/examples.sh +56 -0
  8. stac_api_protocol-0.1.1/demo/pyproject.toml +36 -0
  9. stac_api_protocol-0.1.1/demo/stac_api_demo/__init__.py +15 -0
  10. stac_api_protocol-0.1.1/demo/stac_api_demo/service.py +231 -0
  11. stac_api_protocol-0.1.1/demo/start.sh +19 -0
  12. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/pyproject.toml +37 -18
  13. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/src/stac_api_protocol/__about__.py +1 -1
  14. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/src/stac_api_protocol/main.py +39 -2
  15. stac_api_protocol-0.1.1/tests/test_bbox_queries.py +136 -0
  16. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/.gitignore +0 -0
  17. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/LICENSE +0 -0
  18. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/explanation/architecture.md +0 -0
  19. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/explanation/index.md +0 -0
  20. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/how-to/index.md +0 -0
  21. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/how-to/install.md +0 -0
  22. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/how-to/register-service.md +0 -0
  23. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/how-to/use-cli.md +0 -0
  24. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/index.md +0 -0
  25. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/reference/api.md +0 -0
  26. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/reference/index.md +0 -0
  27. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/tutorials/first-steps.md +0 -0
  28. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/docs/tutorials/index.md +0 -0
  29. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/src/stac_api_protocol/__init__.py +0 -0
  30. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/src/stac_api_protocol/models.py +0 -0
  31. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/src/stac_api_protocol/plugin_loader.py +0 -0
  32. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/src/stac_api_protocol/py.typed +0 -0
  33. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/src/stac_api_protocol/stac_service.py +0 -0
  34. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/tests/conftest.py +0 -0
  35. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/tests/test_models.py +0 -0
  36. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/tests/test_plugin_loader.py +0 -0
  37. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/tests/test_routes.py +0 -0
  38. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/tests/test_search_validation.py +0 -0
  39. {stac_api_protocol-0.1.0 → stac_api_protocol-0.1.1}/tests/test_stac_service.py +0 -0
@@ -23,7 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
23
23
 
24
24
  ## [Unreleased]
25
25
 
26
- ### Added
26
+ ## [0.1.1] - 2026-11-14
27
27
 
28
28
  ### Changed
29
29
 
@@ -33,9 +33,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
33
33
 
34
34
  ### Fixed
35
35
 
36
- ### Security
36
+ - `bbox` not accepted as 4 or 6 CVS (encoded) HTTP query string parameter
37
37
 
38
- ### Added
38
+ ### Security
39
39
 
40
40
  ## [0.1.0] - 2026-01-01
41
41
 
@@ -43,5 +43,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
43
43
 
44
44
  - Initial project release.
45
45
 
46
- [Unreleased]: https://github.com/Terradue/stac-api-protocol/compare/0.1.0...HEAD
46
+ [Unreleased]: https://github.com/Terradue/stac-api-protocol/compare/0.1.1...HEAD
47
+ [0.1.1]: https://github.com/Terradue/stac-api-protocol/compare/0.1.0...0.1.1
47
48
  [0.1.0]: https://github.com/Terradue/stac-api-protocol/releases/tag/0.1.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: stac-api-protocol
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: A Python FastAPI HTTP adapter for STAC API Core, Item Search, Features and Collections.
5
5
  Project-URL: Documentation, https://terradue.github.io/stac-api-protocol/
6
6
  Project-URL: Issues, https://github.com/Terradue/stac-api-protocol/issues
@@ -92,3 +92,8 @@ task quality:pre-commit:run
92
92
  ## License
93
93
 
94
94
  [![Apache License, Version 2.0](https://img.shields.io/badge/license-Apache%20License%202.0-blue)](https://www.apache.org/licenses/LICENSE-2.0)
95
+
96
+ ## GeoParquet demo
97
+
98
+ See [demo/README.md](demo/README.md) for a runnable NAIP-backed `StacApiService`,
99
+ Uvicorn launch command, and curl/jq examples for every API operation.
@@ -62,3 +62,8 @@ task quality:pre-commit:run
62
62
  ## License
63
63
 
64
64
  [![Apache License, Version 2.0](https://img.shields.io/badge/license-Apache%20License%202.0-blue)](https://www.apache.org/licenses/LICENSE-2.0)
65
+
66
+ ## GeoParquet demo
67
+
68
+ See [demo/README.md](demo/README.md) for a runnable NAIP-backed `StacApiService`,
69
+ Uvicorn launch command, and curl/jq examples for every API operation.
@@ -0,0 +1 @@
1
+ data/
@@ -0,0 +1,50 @@
1
+ # NAIP GeoParquet demo
2
+
3
+ A small `StacApiService` implementation using the existing FastAPI adapter.
4
+ Collection metadata comes from `collections.json`; item queries use DuckDB and
5
+ `pygeofilter-duckdb` over `naip.parquet` from the
6
+ [Development Seed sample data](https://github.com/developmentseed/labs-375-stac-geoparquet-backend/tree/main/data).
7
+
8
+ From the repository root, with Python 3.11 or newer:
9
+
10
+ ```bash
11
+ cd demo
12
+ uv venv
13
+ uv pip install -e .. -e .
14
+
15
+ bash ./download-data.sh
16
+ bash ./start.sh
17
+ ```
18
+
19
+ The demo has its own `pyproject.toml`, which registers the service plugin and
20
+ declares Uvicorn and database dependencies. `demo/start.sh` runs Uvicorn directly
21
+ and forwards all arguments to it.
22
+ Install it in an environment with no other `stacapi.service:item_service` provider.
23
+ Set `STAC_DEMO_DATA_DIR` to an absolute directory to launch outside the repository.
24
+ The download script also honors this variable. Downloads are excluded from Git.
25
+
26
+ In another terminal, with `curl` and `jq` installed:
27
+
28
+ ```bash
29
+ bash demo/examples.sh
30
+ # Or: bash demo/examples.sh http://127.0.0.1:8090
31
+ ```
32
+
33
+ The script makes one request per API operation, including both GET and POST
34
+ search, using an actual NAIP tile and spatial/temporal bounds from the dataset.
35
+ Swagger documentation is available at `/docs`.
36
+
37
+ All five collection descriptions are exposed. Only NAIP items are loaded;
38
+ other listed collections have empty item results. Unknown collections and missing
39
+ individual items return 404. Searches support IDs, collections, bbox, intersects,
40
+ and inclusive datetime instants/intervals (including open bounds). Results are
41
+ sorted by collection and ID, default to 10 items, and have no pagination.
42
+ Six-coordinate boxes use XY only because NAIP footprints have no elevation.
43
+ The original asset and item links are preserved and may point to Planetary Computer.
44
+
45
+ GET `bbox` accepts comma-separated coordinates or repeated query parameters.
46
+ Other GET lists use repeated query parameters, and POST `intersects` is a
47
+ JSON-encoded string. It does not add a CQL
48
+ endpoint; `pygeofilter-duckdb` translates the existing search arguments internally.
49
+ Each query uses its own DuckDB connection. Runtime queries use downloaded local
50
+ files and a preinstalled spatial extension, with no external database server.
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env bash
2
+
3
+ # Copyright 2026 Terradue
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ set -euo pipefail
18
+ # Run from any directory; override the target with STAC_DEMO_DATA_DIR.
19
+ data_dir=${STAC_DEMO_DATA_DIR:-"$(dirname "${BASH_SOURCE[0]}")/data"}
20
+ base=https://raw.githubusercontent.com/developmentseed/labs-375-stac-geoparquet-backend/main/data
21
+ mkdir -p "$data_dir"
22
+ for filename in collections.json naip.parquet; do
23
+ curl --fail --location --show-error "$base/$filename" --output "$data_dir/$filename"
24
+ done
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env bash
2
+
3
+ # Copyright 2026 Terradue
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ set -euo pipefail
18
+ base=${1:-http://127.0.0.1:8090}
19
+ base=${base%/}
20
+
21
+ echo "Catalogue identity and navigation."
22
+ curl --fail --silent --show-error "$base/" | jq .
23
+
24
+ read -p "Press Enter for Advertised conformance classes."
25
+ curl --fail --silent --show-error "$base/conformance" | jq .
26
+
27
+ read -p "Press Enter for Static collection metadata, including datasets not loaded in this demo."
28
+ curl --fail --silent --show-error "$base/collections" | jq .
29
+
30
+ read -p "Press Enter for NAIP's Colorado/Nebraska coverage and acquisition dates."
31
+ curl --fail --silent --show-error "$base/collections/naip" | jq .
32
+
33
+ read -p "Press Enter for Two imagery tiles acquired in 2022."
34
+ curl --fail --silent --show-error --get "$base/collections/naip/items" \
35
+ --data-urlencode 'limit=2' \
36
+ --data-urlencode 'bbox=-103,40,102,42' \
37
+ --data-urlencode 'datetime=2022-01-01T00:00:00Z/2022-12-31T23:59:59Z' \
38
+ | jq .
39
+
40
+ read -p "Press Enter for A real southwest-quarter NAIP tile near the Nebraska/Colorado border."
41
+ item=ne_m_4110264_sw_13_060_20220827
42
+ curl --fail --silent --show-error "$base/collections/naip/items/$item" \
43
+ | jq .
44
+
45
+ read -p "Press Enter to GET search combines collection and item identifiers."
46
+ curl --fail --silent --show-error --get "$base/search" \
47
+ --data-urlencode 'collections=naip' --data-urlencode "ids=$item" \
48
+ | jq .
49
+
50
+ read -p "Press Enter to POST search uses the adapter's JSON-encoded string for intersects."
51
+ jq -n '{collections: ["naip"], limit: 2,
52
+ datetime: "2022-01-01T00:00:00Z/..",
53
+ intersects: ({type: "Point", coordinates: [-102.09, 41.03]} | tojson)}' \
54
+ | curl --fail --silent --show-error "$base/search" \
55
+ --header 'Content-Type: application/json' --data-binary @- \
56
+ | jq .
@@ -0,0 +1,36 @@
1
+ # Copyright 2026 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ [build-system]
16
+ requires = ["hatchling==1.33.0"]
17
+ build-backend = "hatchling.build"
18
+
19
+ [project]
20
+ name = "stac-api-protocol-demo"
21
+ version = "0.1.0"
22
+ description = "A small NAIP GeoParquet service for stac-api-protocol"
23
+ requires-python = ">=3.11"
24
+ dependencies = [
25
+ "stac-api-protocol",
26
+ "duckdb>=1.5,<2",
27
+ "duckdb-extension-spatial>=1.5,<2",
28
+ "pygeofilter-duckdb==0.2.0",
29
+ "uvicorn>=0.54,<1",
30
+ ]
31
+
32
+ [project.entry-points."stacapi.service"]
33
+ item_service = "stac_api_demo.service:get_service"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["stac_api_demo"]
@@ -0,0 +1,15 @@
1
+ # Copyright 2026 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Provide the demo's registered GeoParquet service."""
@@ -0,0 +1,231 @@
1
+ # Copyright 2026 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Serve static collection metadata and query NAIP GeoParquet with DuckDB."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ from datetime import datetime as DateTime
22
+ from functools import cache
23
+ from pathlib import Path
24
+ from typing import TYPE_CHECKING
25
+
26
+ import duckdb
27
+ from pygeofilter import ast, values
28
+ from pygeofilter_duckdb import to_sql_where
29
+ from pystac import Collection, Item, ItemCollection, Link
30
+
31
+ from stac_api_protocol.models import Collections
32
+ from stac_api_protocol.stac_service import StacApiService
33
+
34
+ if TYPE_CHECKING:
35
+ from geojson import GeometryCollection
36
+ from geojson.geometry import Geometry as GeometryGeoJSON
37
+
38
+ # These are STAC Item top-level fields; all other Parquet columns are properties.
39
+ ITEM_FIELDS = frozenset(
40
+ {
41
+ "type",
42
+ "stac_version",
43
+ "stac_extensions",
44
+ "id",
45
+ "geometry",
46
+ "bbox",
47
+ "links",
48
+ "assets",
49
+ "collection",
50
+ }
51
+ )
52
+
53
+
54
+ def _temporal_filters(datetime_value: str) -> list[ast.Node]:
55
+ """Build inclusive time bounds for NAIP's instantaneous acquisitions."""
56
+ start, _, end = datetime_value.partition("/")
57
+ if not end:
58
+ end = start
59
+ filters: list[ast.Node] = []
60
+ if start != "..":
61
+ filters.append(
62
+ ast.GreaterEqual(
63
+ ast.Attribute("datetime"), DateTime.fromisoformat(start.upper()).isoformat()
64
+ )
65
+ )
66
+ if end != "..":
67
+ filters.append(
68
+ ast.LessEqual(
69
+ ast.Attribute("datetime"), DateTime.fromisoformat(end.upper()).isoformat()
70
+ )
71
+ )
72
+ return filters
73
+
74
+
75
+ def _bbox_filter(bbox: list[float]) -> ast.Node:
76
+ """Build a 2D spatial predicate, including antimeridian-crossing bounds.
77
+
78
+ NAIP footprints have no vertical dimension; six-value boxes use XY bounds.
79
+
80
+ Raises:
81
+ ValueError: If the box has neither four nor six coordinates.
82
+ """
83
+ dimensions = len(bbox) // 2
84
+ if dimensions not in (2, 3) or len(bbox) != dimensions * 2:
85
+ raise ValueError("Expected four or six bbox coordinates")
86
+ west, south, east, north = bbox[0], bbox[1], bbox[dimensions], bbox[dimensions + 1]
87
+ geometry = ast.Attribute("geometry")
88
+ if west > east:
89
+ return ast.Or(
90
+ ast.BBox(geometry, west, south, 180, north),
91
+ ast.BBox(geometry, -180, south, east, north),
92
+ )
93
+ return ast.BBox(geometry, west, south, east, north)
94
+
95
+
96
+ def _read_item(payload: str) -> Item:
97
+ """Restore nested STAC properties from a flattened GeoParquet row."""
98
+ record = json.loads(payload)
99
+ record["properties"] = {
100
+ name: record.pop(name) for name in list(record) if name not in ITEM_FIELDS
101
+ }
102
+ # Parquet structs include null placeholders for assets absent on this item.
103
+ record["assets"] = {
104
+ name: asset for name, asset in record["assets"].items() if asset is not None
105
+ }
106
+ return Item.from_dict(record)
107
+
108
+
109
+ class GeoParquetService(StacApiService):
110
+ """Expose the sample catalogue with NAIP as its only loaded item dataset."""
111
+
112
+ def __init__(self, data_dir: Path) -> None:
113
+ """Read collections.json and locate naip.parquet in a local directory.
114
+
115
+ Args:
116
+ data_dir: Directory populated by the demo's download script.
117
+
118
+ Raises:
119
+ FileNotFoundError: If either required data file is missing.
120
+ """
121
+ super().__init__("naip-demo", "NAIP GeoParquet demo", "NAIP imagery queried with DuckDB")
122
+ self._parquet = data_dir / "naip.parquet"
123
+ if not self._parquet.is_file():
124
+ raise FileNotFoundError(f"Missing {self._parquet}; run bash download-data.sh")
125
+ self._collections = {
126
+ collection.id: collection
127
+ for collection in (
128
+ Collection.from_dict(record)
129
+ for record in json.loads((data_dir / "collections.json").read_text())
130
+ )
131
+ }
132
+
133
+ def get_collections(self) -> Collections:
134
+ """Return all static collection descriptions, including metadata-only datasets."""
135
+ return Collections(
136
+ collections=[collection.clone() for collection in self._collections.values()],
137
+ links=[Link("self", "/collections"), Link("root", "/")],
138
+ )
139
+
140
+ def describe_collection(self, collection_id: str) -> Collection | None:
141
+ """Return an independent collection description, or None for an unknown ID."""
142
+ collection = self._collections.get(collection_id)
143
+ return collection.clone() if collection is not None else None
144
+
145
+ def get_features(
146
+ self,
147
+ collection_id: str,
148
+ limit: int | None,
149
+ bbox: list[float] | None,
150
+ datetime: str | None,
151
+ ) -> ItemCollection | None:
152
+ """Return a collection's matching items, or None for an unknown collection."""
153
+ if collection_id not in self._collections:
154
+ return None
155
+ return self.get_item_search(bbox, None, datetime, limit, None, [collection_id])
156
+
157
+ def get_feature(self, collection_id: str, feature_id: str) -> Item | None:
158
+ """Look up an item by both collection and item ID, returning None if absent."""
159
+ result = self.get_item_search(None, None, None, 1, [feature_id], [collection_id])
160
+ return next(iter(result), None)
161
+
162
+ def get_item_search(
163
+ self,
164
+ bbox: list[float] | None,
165
+ intersects: GeometryGeoJSON | GeometryCollection | None,
166
+ datetime: str | None,
167
+ limit: int | None,
168
+ ids: list[str] | None,
169
+ collections: list[str] | None,
170
+ ) -> ItemCollection:
171
+ """Search NAIP using conjunctive filters and a deterministic, limited result.
172
+
173
+ Unloaded collections and unmatched criteria produce an empty collection.
174
+ The demo returns at most 10 items by default and does not paginate.
175
+ """
176
+ filters: list[ast.Node] = []
177
+ for field, choices in (("id", ids), ("collection", collections)):
178
+ if choices is not None:
179
+ if not choices:
180
+ return ItemCollection([])
181
+ filters.append(ast.In(ast.Attribute(field), list(choices), False))
182
+ if bbox is not None:
183
+ filters.append(_bbox_filter(bbox))
184
+ if intersects is not None:
185
+ filters.append(
186
+ ast.GeometryIntersects(ast.Attribute("geometry"), values.Geometry(intersects))
187
+ )
188
+ if datetime is not None:
189
+ filters.extend(_temporal_filters(datetime))
190
+ return self._query(filters, limit if limit is not None else 10)
191
+
192
+ def _query(self, filters: list[ast.Node], limit: int) -> ItemCollection:
193
+ """Query using a fresh connection so concurrent requests share no cursor."""
194
+ with duckdb.connect(config={"threads": 1}) as connection:
195
+ connection.execute("INSTALL spatial")
196
+ connection.load_extension("spatial")
197
+ connection.execute("SET TimeZone = 'UTC'")
198
+ records = connection.read_parquet(str(self._parquet))
199
+ for predicate in filters:
200
+ # Only server-selected fields and escaped literals reach this SQL API.
201
+ records = records.filter(
202
+ to_sql_where(
203
+ predicate,
204
+ {
205
+ "id": "id",
206
+ "collection": "collection",
207
+ "geometry": "geometry",
208
+ "datetime": "datetime",
209
+ },
210
+ )
211
+ )
212
+ records = (
213
+ records.order('"collection", "id"')
214
+ .limit(limit)
215
+ .project(
216
+ "* REPLACE (ST_AsGeoJSON(geometry)::JSON AS geometry, "
217
+ "[bbox.xmin, bbox.ymin, bbox.xmax, bbox.ymax] AS bbox)"
218
+ )
219
+ )
220
+ rows = (
221
+ records.to_view("results")
222
+ .query("results", "SELECT to_json(results) FROM results")
223
+ .fetchall()
224
+ )
225
+ return ItemCollection([_read_item(row[0]) for row in rows])
226
+
227
+
228
+ @cache
229
+ def get_service() -> GeoParquetService:
230
+ """Load the demo service once, using STAC_DEMO_DATA_DIR or demo/data."""
231
+ return GeoParquetService(Path(os.environ.get("STAC_DEMO_DATA_DIR", "./data")))
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env bash
2
+
3
+ # Copyright 2026 Terradue
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ set -euo pipefail
18
+
19
+ exec uv run --no-project uvicorn stac_api_protocol.main:app --host 0.0.0.0 --port 8090
@@ -68,6 +68,7 @@ include = [
68
68
  "/src",
69
69
  "/tests",
70
70
  "/docs",
71
+ "/demo",
71
72
  "/README.md",
72
73
  "/CHANGELOG.md",
73
74
  "/LICENSE",
@@ -116,8 +117,12 @@ skip-install = false
116
117
  dependencies = [
117
118
  "pytest==9.2.0",
118
119
  "pytest-cov==7.1.0",
120
+ "stac-api-protocol-demo @ {root:uri}/demo",
119
121
  ]
120
122
 
123
+ [tool.hatch.envs.test.env-vars]
124
+ PYTHONPATH = "{root}/demo"
125
+
121
126
  [tool.hatch.envs.test.scripts]
122
127
  test = "pytest {args:tests}"
123
128
  testv = "pytest --verbose {args:tests}"
@@ -149,6 +154,7 @@ xfail_strict = true
149
154
  [tool.hatch.envs.dev]
150
155
  skip-install = false
151
156
  dependencies = [
157
+ "stac-api-protocol-demo @ {root:uri}/demo",
152
158
  "mypy==2.4.1",
153
159
  "types-geojson==3.3.0.20261006",
154
160
  "ruff==0.17.4",
@@ -156,6 +162,9 @@ dependencies = [
156
162
  "pytest==9.2.0",
157
163
  ]
158
164
 
165
+ [tool.hatch.envs.dev.env-vars]
166
+ PYTHONPATH = "{root}/demo"
167
+
159
168
  # ---------------------------------------------------------------------------
160
169
  # Ruff
161
170
  # ---------------------------------------------------------------------------
@@ -220,6 +229,8 @@ extend-immutable-calls = ["fastapi.Depends", "fastapi.Query"]
220
229
  [tool.ruff.lint.per-file-ignores]
221
230
  # OpenAPI-generated signatures and HTTP status literals mirror the API schema.
222
231
  "src/stac_api_protocol/**/*.py" = ["PLR0913", "PLR2004"]
232
+ # Implementations must preserve the protocol's search method signature.
233
+ "demo/stac_api_demo/service.py" = ["PLR0913"]
223
234
 
224
235
  [tool.ruff.lint.mccabe]
225
236
  # Flag errors (C901) whenever complexity exceeds 10 (default is 10)
@@ -240,6 +251,8 @@ max-statements = 40
240
251
 
241
252
  # Strict typing is the default for new Terradue Python projects.
242
253
  strict = true
254
+ # Attribute's constructor is unannotated upstream; its input is a field name.
255
+ untyped_calls_exclude = ["pygeofilter.ast.Attribute"]
243
256
 
244
257
  # Improve diagnostics.
245
258
  pretty = true
@@ -253,9 +266,15 @@ ignore_missing_imports = false
253
266
  # Files checked by default.
254
267
  files = [
255
268
  "src/stac_api_protocol",
256
- "tests"
269
+ "tests",
270
+ "demo/stac_api_demo"
257
271
  ]
258
272
 
273
+ # These dependencies ship annotations but do not declare a py.typed marker.
274
+ [[tool.mypy.overrides]]
275
+ module = ["pygeofilter.*", "pygeofilter_duckdb.*"]
276
+ follow_untyped_imports = true
277
+
259
278
  [tool.hatch.envs.dev.scripts]
260
279
  # ---------------------------------------------------------------------------
261
280
  # Developer commands
@@ -263,11 +282,11 @@ files = [
263
282
  # These commands are allowed to modify files.
264
283
  # ---------------------------------------------------------------------------
265
284
 
266
- format = "ruff format {args:src tests}"
285
+ format = "ruff format {args:src tests demo/stac_api_demo}"
267
286
 
268
287
  fix = [
269
- "ruff check --fix {args:src tests}",
270
- "ruff format {args:src tests}",
288
+ "ruff check --fix {args:src tests demo/stac_api_demo}",
289
+ "ruff format {args:src tests demo/stac_api_demo}",
271
290
  ]
272
291
 
273
292
  # ---------------------------------------------------------------------------
@@ -276,30 +295,30 @@ fix = [
276
295
  # These commands MUST NOT modify files and are suitable for CI.
277
296
  # ---------------------------------------------------------------------------
278
297
 
279
- format-check = "ruff format --check {args:src tests}"
298
+ format-check = "ruff format --check {args:src tests demo/stac_api_demo}"
280
299
 
281
- lint = "ruff check {args:src tests}"
282
- lint-check = "ruff check {args:src tests}"
283
- design-check = "ruff check --select C90,PLR {args:src tests}"
300
+ lint = "ruff check {args:src tests demo/stac_api_demo}"
301
+ lint-check = "ruff check {args:src tests demo/stac_api_demo}"
302
+ design-check = "ruff check --select C90,PLR {args:src tests demo/stac_api_demo}"
284
303
 
285
- typecheck = "mypy {args:src tests}"
304
+ typecheck = "mypy {args:src tests demo/stac_api_demo}"
286
305
 
287
- security = "bandit -r {args:src}"
306
+ security = "bandit -r {args:src demo/stac_api_demo}"
288
307
 
289
308
  # Run the complete static quality gate.
290
309
  quality = [
291
- "ruff format --check {args:src tests}",
292
- "ruff check {args:src tests}",
293
- "mypy {args:src tests}",
294
- "bandit -r {args:src}",
310
+ "ruff format --check {args:src tests demo/stac_api_demo}",
311
+ "ruff check {args:src tests demo/stac_api_demo}",
312
+ "mypy {args:src tests demo/stac_api_demo}",
313
+ "bandit -r {args:src demo/stac_api_demo}",
295
314
  ]
296
315
 
297
316
  # Complete local/CI validation including tests.
298
317
  check = [
299
- "ruff format --check {args:src tests}",
300
- "ruff check {args:src tests}",
301
- "mypy {args:src tests}",
302
- "bandit -r {args:src}",
318
+ "ruff format --check {args:src tests demo/stac_api_demo}",
319
+ "ruff check {args:src tests demo/stac_api_demo}",
320
+ "mypy {args:src tests demo/stac_api_demo}",
321
+ "bandit -r {args:src demo/stac_api_demo}",
303
322
  "pytest {args:tests}",
304
323
  ]
305
324
 
@@ -14,4 +14,4 @@
14
14
 
15
15
  """Package metadata for STAC API Protocol."""
16
16
 
17
- __version__ = "0.1.0"
17
+ __version__ = "0.1.1"
@@ -19,6 +19,7 @@
19
19
  """Expose STAC routes backed by the configured service provider."""
20
20
 
21
21
  import logging
22
+ import math
22
23
  import re
23
24
  from datetime import datetime as DateTime
24
25
  from typing import TYPE_CHECKING, Annotated
@@ -28,6 +29,7 @@ from fastapi.exceptions import RequestValidationError
28
29
  from fastapi.responses import JSONResponse
29
30
  from geojson import GeometryCollection, loads
30
31
  from geojson.geometry import Geometry as GeometryGeoJSON
32
+ from pydantic import AfterValidator, BeforeValidator
31
33
  from starlette.exceptions import HTTPException as StarletteHTTPException
32
34
 
33
35
  if TYPE_CHECKING:
@@ -215,6 +217,31 @@ def describe_collection(
215
217
  raise _not_found(f"Collection {collection_id} does not exist in this Catalogue")
216
218
 
217
219
 
220
+ def _split_bbox_coordinates(value: object) -> object:
221
+ """Expand comma-separated query values while retaining repeated parameters."""
222
+ if not isinstance(value, list):
223
+ return value
224
+ return [
225
+ coordinate
226
+ for entry in value
227
+ for coordinate in (entry.split(",") if isinstance(entry, str) else [entry])
228
+ ]
229
+
230
+
231
+ def _validate_bbox_coordinates(bbox: list[float] | None) -> list[float] | None:
232
+ """Require four or six finite coordinates for a query bounding box.
233
+
234
+ Raises:
235
+ ValueError: If the bounding box has an invalid size or non-finite values.
236
+ """
237
+ if bbox is not None:
238
+ if len(bbox) not in (4, 6):
239
+ raise ValueError("Bounding box must contain four or six coordinates")
240
+ if not all(math.isfinite(coordinate) for coordinate in bbox):
241
+ raise ValueError("Bounding box coordinates must be finite")
242
+ return bbox
243
+
244
+
218
245
  @app.get(
219
246
  "/collections/{collectionId}/items",
220
247
  responses={"4XX": {"model": StacException}, "5XX": {"model": StacException}},
@@ -223,7 +250,12 @@ def describe_collection(
223
250
  def get_features(
224
251
  collection_id: str = Path(..., alias="collectionId"),
225
252
  limit: Annotated[int | None, Query(ge=1, le=10000)] = 10,
226
- bbox: list[float] | None = Query(None),
253
+ bbox: Annotated[
254
+ list[float] | None,
255
+ BeforeValidator(_split_bbox_coordinates),
256
+ AfterValidator(_validate_bbox_coordinates),
257
+ Query(min_length=4, max_length=6),
258
+ ] = None,
227
259
  datetime: str | None = None,
228
260
  service: StacApiService = Depends(get_item_service),
229
261
  ) -> Response:
@@ -354,7 +386,12 @@ def _parse_intersects(value: str | None) -> GeometryGeoJSON | GeometryCollection
354
386
  tags=["Item Search"],
355
387
  )
356
388
  def get_item_search(
357
- bbox: list[float] | None = Query(None, min_length=4, max_length=6),
389
+ bbox: Annotated[
390
+ list[float] | None,
391
+ BeforeValidator(_split_bbox_coordinates),
392
+ AfterValidator(_validate_bbox_coordinates),
393
+ Query(min_length=4, max_length=6),
394
+ ] = None,
358
395
  intersects: str | None = None,
359
396
  datetime: str | None = None,
360
397
  limit: Annotated[int | None, Query(ge=1, le=10000)] = 10,
@@ -0,0 +1,136 @@
1
+ # Copyright 2026 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Exercise query decoding through ASGI rather than calling routes directly."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import json
21
+ from http import HTTPStatus
22
+ from typing import TYPE_CHECKING
23
+
24
+ import pytest
25
+ from pystac import ItemCollection
26
+
27
+ if TYPE_CHECKING:
28
+ from collections.abc import Iterator
29
+ from types import ModuleType
30
+ from unittest.mock import Mock
31
+
32
+ from fastapi import FastAPI
33
+ from starlette.types import Message, Scope
34
+
35
+
36
+ @pytest.fixture
37
+ def bbox_app(api: ModuleType, service: Mock) -> Iterator[FastAPI]:
38
+ app: FastAPI = api.app
39
+ service.get_features.return_value = ItemCollection([])
40
+ service.get_item_search.return_value = ItemCollection([])
41
+ app.dependency_overrides[api.get_item_service] = lambda: service
42
+ yield app
43
+ app.dependency_overrides.pop(api.get_item_service)
44
+
45
+
46
+ async def _get_query(app: FastAPI, path: str, query: str) -> tuple[HTTPStatus, str]:
47
+ """Send an HTTP query through FastAPI's complete validation pipeline."""
48
+ response_status = HTTPStatus.INTERNAL_SERVER_ERROR
49
+ response_body = bytearray()
50
+
51
+ async def receive() -> Message:
52
+ return {"type": "http.request", "body": b"", "more_body": False}
53
+
54
+ async def send(message: Message) -> None:
55
+ nonlocal response_status
56
+ if message["type"] == "http.response.start":
57
+ response_status = HTTPStatus(message["status"])
58
+ elif message["type"] == "http.response.body":
59
+ response_body.extend(message["body"])
60
+
61
+ scope: Scope = {
62
+ "type": "http",
63
+ "asgi": {"version": "3.0"},
64
+ "http_version": "1.1",
65
+ "method": "GET",
66
+ "scheme": "http",
67
+ "path": path,
68
+ "raw_path": path.encode(),
69
+ "query_string": query.encode(),
70
+ "root_path": "",
71
+ "headers": [],
72
+ "server": ("localhost", 8000),
73
+ "client": ("127.0.0.1", 1),
74
+ }
75
+ await app(scope, receive, send)
76
+ return response_status, response_body.decode()
77
+
78
+
79
+ @pytest.mark.parametrize("path", ["/collections/naip/items", "/search"])
80
+ @pytest.mark.parametrize(
81
+ ("query", "expected"),
82
+ [
83
+ ("", None),
84
+ ("bbox=-103%2C40%2C102%2C42", [-103, 40, 102, 42]),
85
+ ("bbox=-103,40,102,42", [-103, 40, 102, 42]),
86
+ ("bbox=-103,40,0,-102,42,100", [-103, 40, 0, -102, 42, 100]),
87
+ ("bbox=-103&bbox=40&bbox=-102&bbox=42", [-103, 40, -102, 42]),
88
+ (
89
+ "bbox=-103&bbox=40&bbox=0&bbox=-102&bbox=42&bbox=100",
90
+ [-103, 40, 0, -102, 42, 100],
91
+ ),
92
+ ],
93
+ )
94
+ def test_bbox_query_encodings_reach_service(
95
+ bbox_app: FastAPI, service: Mock, path: str, query: str, expected: list[float] | None
96
+ ) -> None:
97
+ datetime_value = "2022-01-01T00:00:00Z/2022-12-31T23:59:59Z"
98
+ query += "&limit=2&datetime=2022-01-01T00%3A00%3A00Z%2F2022-12-31T23%3A59%3A59Z"
99
+ status, body = asyncio.run(_get_query(bbox_app, path, query))
100
+ assert status == HTTPStatus.OK
101
+ assert json.loads(body)["type"] == "FeatureCollection"
102
+ if path == "/search":
103
+ service.get_item_search.assert_called_once_with(
104
+ expected, None, datetime_value, 2, None, None
105
+ )
106
+ else:
107
+ service.get_features.assert_called_once_with("naip", 2, expected, datetime_value)
108
+
109
+
110
+ @pytest.mark.parametrize("path", ["/collections/naip/items", "/search"])
111
+ @pytest.mark.parametrize(
112
+ "query",
113
+ [
114
+ "bbox=",
115
+ "bbox=-103,40,42",
116
+ "bbox=-103,40,-102,42,100",
117
+ "bbox=-103,40,0,-102,42,100,200",
118
+ "bbox=-103,40,invalid,42",
119
+ "bbox=-103,40,,42",
120
+ "bbox=-103,40,-102,42,",
121
+ "bbox=-103,40,nan,42",
122
+ "bbox=-103,40,inf,42",
123
+ "bbox=-103,40,1e999,42",
124
+ "bbox=-103&bbox=40&bbox=invalid&bbox=42",
125
+ ],
126
+ )
127
+ def test_invalid_bbox_queries_do_not_reach_service(
128
+ bbox_app: FastAPI, service: Mock, path: str, query: str
129
+ ) -> None:
130
+ status, body = asyncio.run(_get_query(bbox_app, path, query))
131
+ assert status == HTTPStatus.UNPROCESSABLE_ENTITY
132
+ error = json.loads(body)
133
+ assert error["code"] == "422"
134
+ assert "query.bbox" in error["description"]
135
+ service.get_features.assert_not_called()
136
+ service.get_item_search.assert_not_called()