stac-api-protocol 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,17 @@
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
+ """Package metadata for STAC API Protocol."""
16
+
17
+ __version__ = "0.1.0"
@@ -0,0 +1,19 @@
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
+ """A Python FastAPI HTTP adapter for STAC API Core, Item Search, Features and Collections."""
16
+
17
+ from stac_api_protocol.__about__ import __version__
18
+
19
+ __all__ = ["__version__"]
@@ -0,0 +1,398 @@
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
+ # generated by fastapi-codegen:
16
+ # filename: openapi.yaml
17
+ # timestamp: 2026-11-11T13:01:33+00:00
18
+
19
+ """Expose STAC routes backed by the configured service provider."""
20
+
21
+ import logging
22
+ import re
23
+ from datetime import datetime as DateTime
24
+ from typing import TYPE_CHECKING, Annotated
25
+
26
+ from fastapi import Depends, FastAPI, HTTPException, Path, Query, Request, Response, status
27
+ from fastapi.exceptions import RequestValidationError
28
+ from fastapi.responses import JSONResponse
29
+ from geojson import GeometryCollection, loads
30
+ from geojson.geometry import Geometry as GeometryGeoJSON
31
+ from starlette.exceptions import HTTPException as StarletteHTTPException
32
+
33
+ if TYPE_CHECKING:
34
+ from pystac import Collection, Item, ItemCollection
35
+
36
+ from .models import Collections, ConformanceClasses, LandingPage, SearchBody
37
+ from .models import Exception as StacException
38
+ from .plugin_loader import load_dependency
39
+ from .stac_service import StacApiService
40
+
41
+ get_item_service = load_dependency("item_service")
42
+
43
+
44
+ app = FastAPI(
45
+ title="STAC API - Bundle",
46
+ version="1.0.0",
47
+ description="Bundled version of STAC API Core, Item Search, Features and Collections",
48
+ contact={"name": "STAC Specification", "url": "http://stacspec.org"},
49
+ license_info={
50
+ "name": "Apache License 2.0",
51
+ "url": "https://www.apache.org/licenses/LICENSE-2.0",
52
+ },
53
+ servers=[{"description": "Example Server 1", "url": "https://terradue.com/stacapi"}],
54
+ )
55
+
56
+
57
+ @app.exception_handler(StarletteHTTPException)
58
+ async def http_exception_handler(_request: Request, error: StarletteHTTPException) -> JSONResponse:
59
+ """Return application and framework HTTP errors using the STAC error schema."""
60
+ return JSONResponse(
61
+ status_code=error.status_code,
62
+ headers=error.headers,
63
+ content=StacException(
64
+ code=str(error.status_code), description=str(error.detail)
65
+ ).model_dump(mode="json", exclude_none=True),
66
+ )
67
+
68
+
69
+ @app.exception_handler(RequestValidationError)
70
+ async def validation_exception_handler(
71
+ _request: Request, error: RequestValidationError
72
+ ) -> JSONResponse:
73
+ """Return request validation failures using the STAC error schema."""
74
+ description = "; ".join(
75
+ f"{'.'.join(str(part) for part in issue['loc'])}: {issue['msg']}"
76
+ for issue in error.errors()
77
+ )
78
+ return JSONResponse(
79
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
80
+ content=StacException(code="422", description=description).model_dump(mode="json"),
81
+ )
82
+
83
+
84
+ @app.exception_handler(Exception)
85
+ async def unexpected_exception_handler(_request: Request, error: Exception) -> JSONResponse:
86
+ """Log unexpected application failures and return a generic STAC error."""
87
+ logging.getLogger(__name__).error("Unhandled application error", exc_info=error)
88
+ return JSONResponse(
89
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
90
+ content=StacException(code="500", description="Internal Server Error").model_dump(
91
+ mode="json"
92
+ ),
93
+ )
94
+
95
+
96
+ def _http_exception(code: int, description: str) -> HTTPException:
97
+ return HTTPException(status_code=code, detail=description)
98
+
99
+
100
+ def _not_found(description: str) -> HTTPException:
101
+ return _http_exception(status.HTTP_404_NOT_FOUND, description)
102
+
103
+
104
+ def _server_error(description: str) -> HTTPException:
105
+ return _http_exception(status.HTTP_500_INTERNAL_SERVER_ERROR, description)
106
+
107
+
108
+ def _parse_datetime_bound(value: str) -> DateTime:
109
+ """Parse a timezone-qualified RFC 3339 timestamp.
110
+
111
+ Raises:
112
+ ValueError: If the timestamp has invalid syntax or calendar values.
113
+ """
114
+ pattern = (
115
+ r"[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt](?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]"
116
+ r"(?:\.[0-9]+)?(?:[Zz]|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])"
117
+ )
118
+ if re.fullmatch(pattern, value) is None:
119
+ raise ValueError("Expected an RFC 3339 timestamp with a timezone")
120
+ return DateTime.fromisoformat(value.upper())
121
+
122
+
123
+ def _validate_datetime_interval(value: str) -> None:
124
+ """Check interval bounds, raising ValueError for invalid or reversed bounds."""
125
+ start_value, end_value = value.split("/")
126
+ start = None if start_value == ".." else _parse_datetime_bound(start_value)
127
+ end = None if end_value == ".." else _parse_datetime_bound(end_value)
128
+ if start is None and end is None:
129
+ raise ValueError("At least one interval bound must be a timestamp")
130
+ if start is not None and end is not None and start > end:
131
+ raise ValueError("Interval start must not be after its end")
132
+
133
+
134
+ def _validate_datetime(datetime_value: str | None) -> None:
135
+ """Validate an optional instant or interval before invoking the service.
136
+
137
+ Interval bounds may be open using ``..``; at least one must be finite.
138
+ Closed intervals must have their start at or before their end.
139
+
140
+ Raises:
141
+ HTTPException: With status 400 when the datetime filter is invalid.
142
+ """
143
+ if datetime_value is None:
144
+ return
145
+ try:
146
+ if "/" not in datetime_value:
147
+ _parse_datetime_bound(datetime_value)
148
+ return
149
+ _validate_datetime_interval(datetime_value)
150
+ except ValueError as error:
151
+ raise _http_exception(
152
+ code=status.HTTP_400_BAD_REQUEST,
153
+ description=f"Invalid datetime: {error}",
154
+ ) from error
155
+
156
+
157
+ @app.get(
158
+ "/",
159
+ responses={"4XX": {"model": StacException}, "5XX": {"model": StacException}},
160
+ tags=["Core"],
161
+ )
162
+ def get_landing_page(
163
+ request: Request, service: StacApiService = Depends(get_item_service)
164
+ ) -> Response:
165
+ """Return the configured service catalogue landing page."""
166
+ try:
167
+ landing_page: LandingPage = service.get_landing_page(request)
168
+ except Exception as e:
169
+ raise _server_error(f"An error occurred when looking for the Landing Page: {e}") from e
170
+
171
+ if landing_page:
172
+ return JSONResponse(content=landing_page.to_dict())
173
+
174
+ raise _not_found("Landing Page does not exist in this Catalogue")
175
+
176
+
177
+ @app.get(
178
+ "/collections",
179
+ response_model=Collections,
180
+ responses={"4XX": {"model": StacException}, "5XX": {"model": StacException}},
181
+ tags=["Collections"],
182
+ )
183
+ def get_collections(service: StacApiService = Depends(get_item_service)) -> Collections:
184
+ """List collections from the configured service."""
185
+ try:
186
+ return service.get_collections()
187
+ except Exception as e:
188
+ raise _server_error(
189
+ f"An error occurred when retrieving the Collections for the current Catalogue: {e}"
190
+ ) from e
191
+
192
+
193
+ @app.get(
194
+ "/collections/{collectionId}",
195
+ responses={"4XX": {"model": StacException}, "5XX": {"model": StacException}},
196
+ tags=["Collections"],
197
+ )
198
+ def describe_collection(
199
+ collection_id: str = Path(..., alias="collectionId"),
200
+ service: StacApiService = Depends(get_item_service),
201
+ ) -> Response:
202
+ """Return collection metadata or raise an HTTP error when unavailable."""
203
+ collection: Collection | None = None
204
+
205
+ try:
206
+ collection = service.describe_collection(collection_id)
207
+ except Exception as e:
208
+ raise _server_error(
209
+ f"An error occurred when looking for Collection {collection_id}: {e}"
210
+ ) from e
211
+
212
+ if collection:
213
+ return JSONResponse(content=collection.to_dict())
214
+
215
+ raise _not_found(f"Collection {collection_id} does not exist in this Catalogue")
216
+
217
+
218
+ @app.get(
219
+ "/collections/{collectionId}/items",
220
+ responses={"4XX": {"model": StacException}, "5XX": {"model": StacException}},
221
+ tags=["Features"],
222
+ )
223
+ def get_features(
224
+ collection_id: str = Path(..., alias="collectionId"),
225
+ limit: Annotated[int | None, Query(ge=1, le=10000)] = 10,
226
+ bbox: list[float] | None = Query(None),
227
+ datetime: str | None = None,
228
+ service: StacApiService = Depends(get_item_service),
229
+ ) -> Response:
230
+ """Return collection items matching the supplied filters."""
231
+ _validate_datetime(datetime)
232
+ search_result: ItemCollection | None = None
233
+
234
+ try:
235
+ search_result = service.get_features(
236
+ collection_id,
237
+ limit,
238
+ bbox,
239
+ datetime,
240
+ )
241
+ except Exception as e:
242
+ raise _server_error(
243
+ f"An error occurred when getting Features from Collection {collection_id} with criteria: limit={limit}, bbox={bbox}, datetime={datetime}: {e}"
244
+ ) from e
245
+
246
+ if search_result is not None:
247
+ return JSONResponse(content=search_result.to_dict())
248
+
249
+ raise _not_found(
250
+ f"Getting Features from Collection {collection_id} with criteria: limit={limit}, bbox={bbox}, datetime={datetime} did not produce any result"
251
+ )
252
+
253
+
254
+ @app.get(
255
+ "/collections/{collectionId}/items/{featureId}",
256
+ responses={"4XX": {"model": StacException}, "5XX": {"model": StacException}},
257
+ tags=["Features"],
258
+ )
259
+ def get_feature(
260
+ collection_id: str = Path(..., alias="collectionId"),
261
+ feature_id: str = Path(..., alias="featureId"),
262
+ service: StacApiService = Depends(get_item_service),
263
+ ) -> Response:
264
+ """Return an item or raise an HTTP error when unavailable."""
265
+ feature: Item | None = None
266
+
267
+ try:
268
+ feature = service.get_feature(collection_id, feature_id)
269
+ except Exception as e:
270
+ raise _server_error(
271
+ f"An error occurred when looking for Item {feature_id} from Collection {collection_id}: {e}"
272
+ ) from e
273
+
274
+ if feature:
275
+ return JSONResponse(content=feature.to_dict())
276
+
277
+ raise _not_found(
278
+ f"Item {feature_id} does not exist in Collection {collection_id} in this Catalogue"
279
+ )
280
+
281
+
282
+ @app.get(
283
+ "/conformance",
284
+ response_model=ConformanceClasses,
285
+ responses={"4XX": {"model": StacException}, "5XX": {"model": StacException}},
286
+ tags=["Features"],
287
+ )
288
+ def get_conformance_declaration(
289
+ service: StacApiService = Depends(get_item_service),
290
+ ) -> ConformanceClasses:
291
+ """Return the specifications advertised by the configured service."""
292
+ try:
293
+ return service.get_conformance_declaration()
294
+ except Exception as e:
295
+ raise _server_error(
296
+ f"An error occurred when retrieving the Conformance Classes for the current Catalogue: {e}"
297
+ ) from e
298
+
299
+
300
+ def _item_search(
301
+ bbox: list[float] | None,
302
+ intersects: GeometryGeoJSON | GeometryCollection | None,
303
+ datetime: str | None,
304
+ limit: int | None,
305
+ ids: list[str] | None,
306
+ collections: list[str] | None,
307
+ *,
308
+ service: StacApiService,
309
+ ) -> Response:
310
+ """Delegate search and translate missing results and backend errors to HTTP errors."""
311
+ _validate_datetime(datetime)
312
+ search_result: ItemCollection | None = None
313
+
314
+ try:
315
+ search_result = service.get_item_search(bbox, intersects, datetime, limit, ids, collections)
316
+ except Exception as e:
317
+ raise _server_error(
318
+ f"An error occurred when searching with criteria: bbox={bbox}, intersects={intersects}, datetime={datetime}, limit={limit}, ids={ids}, collections={collections}: {e}"
319
+ ) from e
320
+
321
+ if search_result is not None:
322
+ return JSONResponse(content=search_result.to_dict())
323
+
324
+ raise _not_found(
325
+ f"Searching with criteria: bbox={bbox}, intersects={intersects}, datetime={datetime}, limit={limit}, ids={ids}, collections={collections} did not produce any result"
326
+ )
327
+
328
+
329
+ def _parse_intersects(value: str | None) -> GeometryGeoJSON | GeometryCollection | None:
330
+ """Parse search geometry using the GeoJSON library.
331
+
332
+ Raises:
333
+ HTTPException: With status 422 when the input is not a valid geometry.
334
+ """
335
+ if value is None:
336
+ return None
337
+ try:
338
+ # JSON null decodes to None, although the GeoJSON stubs omit that return type.
339
+ geometry: object = loads(value)
340
+ if geometry is None:
341
+ return None
342
+ if not isinstance(geometry, (GeometryGeoJSON, GeometryCollection)) or not geometry.is_valid:
343
+ raise ValueError("Expected a valid GeoJSON geometry")
344
+ except (ValueError, TypeError, AttributeError, KeyError, IndexError) as error:
345
+ raise _http_exception(
346
+ code=status.HTTP_422_UNPROCESSABLE_CONTENT, description="Invalid intersects geometry"
347
+ ) from error
348
+ return geometry
349
+
350
+
351
+ @app.get(
352
+ "/search",
353
+ responses={"4XX": {"model": StacException}, "5XX": {"model": StacException}},
354
+ tags=["Item Search"],
355
+ )
356
+ def get_item_search(
357
+ bbox: list[float] | None = Query(None, min_length=4, max_length=6),
358
+ intersects: str | None = None,
359
+ datetime: str | None = None,
360
+ limit: Annotated[int | None, Query(ge=1, le=10000)] = 10,
361
+ ids: list[str] | None = Query(None),
362
+ collections: list[str] | None = Query(None),
363
+ *,
364
+ service: StacApiService = Depends(get_item_service),
365
+ ) -> Response:
366
+ """Search STAC items using query parameters."""
367
+ return _item_search(
368
+ bbox,
369
+ _parse_intersects(intersects),
370
+ datetime,
371
+ limit,
372
+ ids,
373
+ collections,
374
+ service=service,
375
+ )
376
+
377
+
378
+ @app.post(
379
+ "/search",
380
+ responses={"4XX": {"model": StacException}, "5XX": {"model": StacException}},
381
+ tags=["Item Search"],
382
+ )
383
+ def post_item_search(
384
+ body: SearchBody | None = None, service: StacApiService = Depends(get_item_service)
385
+ ) -> Response:
386
+ """Search STAC items using a validated JSON request body."""
387
+ if not body:
388
+ raise _not_found("No search criteria specified")
389
+
390
+ return _item_search(
391
+ body.bbox,
392
+ _parse_intersects(body.intersects) if body.intersects is not None else None,
393
+ body.datetime,
394
+ body.limit,
395
+ body.ids,
396
+ body.collections,
397
+ service=service,
398
+ )
@@ -0,0 +1,187 @@
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
+ # generated by datamodel-codegen:
16
+ # filename: openapi.yaml
17
+ # timestamp: 2026-11-12T16:03:46+00:00
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Annotated, Any
22
+
23
+ from pydantic import BaseModel, ConfigDict, Field, field_serializer
24
+ from pystac import Catalog, Collection, Link
25
+
26
+
27
+ class ConformanceClasses(BaseModel):
28
+ model_config = ConfigDict(
29
+ extra="allow",
30
+ populate_by_name=True,
31
+ )
32
+ conforms_to: Annotated[list[str], Field(alias="conformsTo")]
33
+ """
34
+ A list of all conformance classes implemented by the server. In addition to the STAC-specific conformance classes, all OGC-related conformance classes listed at `GET /conformance` must be listed here. This entry should mirror what `GET /conformance` returns, if implemented.
35
+ """
36
+
37
+
38
+ class LandingPage(Catalog):
39
+ conforms_to: list[str]
40
+
41
+ def to_dict(
42
+ self, include_self_link: bool = True, transform_hrefs: bool = True
43
+ ) -> dict[str, Any]:
44
+ result = super().to_dict()
45
+ result["conformsTo"] = self.conforms_to
46
+ return result
47
+
48
+
49
+ class Exception(BaseModel):
50
+ """
51
+ Information about the exception: an error code plus an optional description.
52
+ """
53
+
54
+ model_config = ConfigDict(
55
+ extra="allow",
56
+ populate_by_name=True,
57
+ )
58
+ code: str
59
+ description: str | None = None
60
+
61
+
62
+ class Collections(BaseModel):
63
+ model_config = ConfigDict(extra="allow", populate_by_name=True, arbitrary_types_allowed=True)
64
+ links: list[Link]
65
+ collections: list[Collection]
66
+
67
+ @field_serializer("links")
68
+ def serialize_links(self, links: list[Link]) -> list[dict[str, object]]:
69
+ return [link.to_dict() for link in links]
70
+
71
+ @field_serializer("collections")
72
+ def serialize_collections(self, collections: list[Collection]) -> list[dict[str, object]]:
73
+ return [collection.to_dict() for collection in collections]
74
+
75
+
76
+ class BboxFilter(BaseModel):
77
+ bbox: list[float] | None = None
78
+
79
+
80
+ class DatetimeFilter(BaseModel):
81
+ """
82
+ An object representing a date+time based filter.
83
+ """
84
+
85
+ model_config = ConfigDict(
86
+ extra="allow",
87
+ populate_by_name=True,
88
+ )
89
+ datetime: Annotated[
90
+ str | None, Field(examples=["2018-02-12T00:00:00Z/2018-03-18T12:31:12Z"])
91
+ ] = None
92
+ """
93
+ Either a date-time or an interval, open or closed. Date and time expressions
94
+ adhere to RFC 3339. Open intervals are expressed using double-dots.
95
+
96
+ Examples:
97
+
98
+ * A date-time: "2018-02-12T23:20:50Z"
99
+ * A closed interval: "2018-02-12T00:00:00Z/2018-03-18T12:31:12Z"
100
+ * Open intervals: "2018-02-12T00:00:00Z/.." or "../2018-03-18T12:31:12Z"
101
+
102
+ Only features that have a temporal property that intersects the value of
103
+ `datetime` are selected.
104
+
105
+ If a feature has multiple temporal properties, it is the decision of the
106
+ server whether only a single temporal property is used to determine
107
+ the extent or all relevant temporal properties.
108
+ """
109
+
110
+
111
+ class CollectionsFilter(BaseModel):
112
+ """
113
+ Only returns the collections specified
114
+ """
115
+
116
+ model_config = ConfigDict(
117
+ extra="allow",
118
+ populate_by_name=True,
119
+ )
120
+ collections: list[str] | None = None
121
+ """
122
+ Array of Collection IDs to include in the search for items.
123
+ Only Item objects in one of the provided collections will be searched.
124
+ """
125
+
126
+
127
+ class IdsFilter(BaseModel):
128
+ """
129
+ Only returns items that match the array of given ids
130
+ """
131
+
132
+ model_config = ConfigDict(
133
+ extra="allow",
134
+ populate_by_name=True,
135
+ )
136
+ ids: list[str] | None = None
137
+ """
138
+ Array of Item ids to return.
139
+ """
140
+
141
+
142
+ class LimitFilter(BaseModel):
143
+ """
144
+ Only returns maximum number of results (page size)
145
+ """
146
+
147
+ model_config = ConfigDict(
148
+ extra="allow",
149
+ populate_by_name=True,
150
+ )
151
+ limit: Annotated[int | None, Field(examples=[10], ge=1, le=10000)] = 10
152
+ """
153
+ The optional limit parameter limits the number of items that are presented in the response document.
154
+
155
+ If the limit parameter value is greater than advertised limit maximum, the server must return the
156
+ maximum possible number of items, rather than responding with an error.
157
+
158
+ Only items are counted that are on the first level of the collection in the response document.
159
+ Nested objects contained within the explicitly requested items must not be counted.
160
+
161
+ Minimum = 1. Maximum = 10000. Default = 10.
162
+ """
163
+
164
+
165
+ class IntersectsFilter(BaseModel):
166
+ """
167
+ Only returns items that intersect with the provided polygon.
168
+ """
169
+
170
+ model_config = ConfigDict(
171
+ extra="allow",
172
+ populate_by_name=True,
173
+ )
174
+ intersects: str | None = None
175
+
176
+
177
+ class SearchBody(
178
+ BboxFilter, DatetimeFilter, IntersectsFilter, CollectionsFilter, IdsFilter, LimitFilter
179
+ ):
180
+ """
181
+ The search criteria
182
+ """
183
+
184
+ model_config = ConfigDict(
185
+ extra="allow",
186
+ populate_by_name=True,
187
+ )
@@ -0,0 +1,42 @@
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
+ """Load service providers registered through Python entry points."""
16
+
17
+ from collections.abc import Callable
18
+ from importlib.metadata import entry_points
19
+
20
+
21
+ def load_dependency(name: str) -> Callable[..., object]:
22
+ """Load the unique callable provider registered under the given name.
23
+
24
+ Raises:
25
+ RuntimeError: If no provider, multiple providers, or a non-callable
26
+ provider is registered.
27
+ """
28
+ matches = entry_points(
29
+ group="stacapi.service",
30
+ name=name,
31
+ )
32
+
33
+ if not matches:
34
+ raise RuntimeError(f"Missing required dependency: {name}")
35
+
36
+ if len(matches) > 1:
37
+ raise RuntimeError(f"Multiple implementations found for: {name}")
38
+
39
+ provider: object = next(iter(matches)).load()
40
+ if not callable(provider):
41
+ raise RuntimeError(f"Dependency is not callable: {name}")
42
+ return provider
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,116 @@
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
+ """Define catalogue operations and shared landing-page metadata for service providers."""
16
+
17
+ from __future__ import annotations
18
+
19
+ from abc import ABC, abstractmethod
20
+ from typing import TYPE_CHECKING, final
21
+
22
+ from pystac import Link
23
+
24
+ from .models import ConformanceClasses, LandingPage
25
+
26
+ if TYPE_CHECKING:
27
+ from fastapi import Request
28
+ from geojson import GeometryCollection
29
+ from geojson.geometry import Geometry as GeometryGeoJSON
30
+ from pystac import Collection, Item, ItemCollection
31
+
32
+ from .models import Collections
33
+
34
+
35
+ class StacApiService(ABC):
36
+ """Provide shared metadata and require adopter-defined catalogue operations.
37
+
38
+ Attributes:
39
+ id: Stable catalogue identifier.
40
+ title: Human-readable catalogue title.
41
+ description: Description of the catalogue's contents.
42
+ """
43
+
44
+ def __init__(self, id: str, title: str, description: str) -> None:
45
+ """Configure the identity used in the catalogue landing page."""
46
+ self.id = id
47
+ self.title = title
48
+ self.description = description
49
+
50
+ @final
51
+ def get_landing_page(self, request: Request) -> LandingPage:
52
+ """Build metadata and links for the requested catalogue root.
53
+
54
+ Args:
55
+ request: Landing-page request whose URL supplies the public catalogue
56
+ root, including any deployment prefix. Query strings are excluded.
57
+ """
58
+ landing_page = LandingPage(
59
+ id=self.id,
60
+ title=self.title,
61
+ description=self.description,
62
+ )
63
+
64
+ base_url = str(request.url.replace(query="", fragment="")).rstrip("/")
65
+ landing_page.add_link(Link("self", f"{base_url}/"))
66
+ landing_page.add_link(Link("data", f"{base_url}/collections"))
67
+ landing_page.add_link(Link("conformance", f"{base_url}/conformance"))
68
+ landing_page.add_link(Link("search", f"{base_url}/search"))
69
+
70
+ landing_page.conforms_to = self.get_conformance_declaration().conforms_to
71
+ return landing_page
72
+
73
+ @abstractmethod
74
+ def get_collections(self) -> Collections:
75
+ """Return the catalogue's collection listing and navigation links."""
76
+
77
+ @abstractmethod
78
+ def describe_collection(self, collection_id: str) -> Collection | None:
79
+ """Return collection metadata, or None if the collection does not exist."""
80
+
81
+ @abstractmethod
82
+ def get_features(
83
+ self, collection_id: str, limit: int | None, bbox: list[float] | None, datetime: str | None
84
+ ) -> ItemCollection | None:
85
+ """Return matching items, an empty result, or None for an unavailable resource."""
86
+
87
+ @abstractmethod
88
+ def get_feature(self, collection_id: str, feature_id: str) -> Item | None:
89
+ """Return an item, or None if it does not exist in the collection."""
90
+
91
+ @final
92
+ def get_conformance_declaration(self) -> ConformanceClasses:
93
+ """Return a fresh declaration of the four supported STAC API classes.
94
+
95
+ Adopter implementations must fulfill these advertised capabilities.
96
+ """
97
+ return ConformanceClasses(
98
+ conforms_to=[
99
+ "https://api.stacspec.org/v1.0.0/core",
100
+ "https://api.stacspec.org/v1.0.0/item-search",
101
+ "https://api.stacspec.org/v1.0.0/collections",
102
+ "https://api.stacspec.org/v1.0.0/ogcapi-features",
103
+ ]
104
+ )
105
+
106
+ @abstractmethod
107
+ def get_item_search(
108
+ self,
109
+ bbox: list[float] | None,
110
+ intersects: GeometryGeoJSON | GeometryCollection | None,
111
+ datetime: str | None,
112
+ limit: int | None,
113
+ ids: list[str] | None,
114
+ collections: list[str] | None,
115
+ ) -> ItemCollection | None:
116
+ """Return matching items, an empty result, or None for an unavailable resource."""
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.5
2
+ Name: stac-api-protocol
3
+ Version: 0.1.0
4
+ Summary: A Python FastAPI HTTP adapter for STAC API Core, Item Search, Features and Collections.
5
+ Project-URL: Documentation, https://terradue.github.io/stac-api-protocol/
6
+ Project-URL: Issues, https://github.com/Terradue/stac-api-protocol/issues
7
+ Project-URL: Source, https://github.com/Terradue/stac-api-protocol
8
+ Project-URL: Changelog, https://github.com/Terradue/stac-api-protocol/blob/main/CHANGELOG.md
9
+ Author-email: Terradue <info@terradue.com>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3.15
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: fastapi>=0.162.4
24
+ Requires-Dist: geojson==3.3.0
25
+ Requires-Dist: pystac<2,>=1.14
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest-cov==7.1.0; extra == 'test'
28
+ Requires-Dist: pytest==9.2.0; extra == 'test'
29
+ Description-Content-Type: text/markdown
30
+
31
+ <!--
32
+ Copyright 2026 Terradue
33
+
34
+ Licensed under the Apache License, Version 2.0 (the "License");
35
+ you may not use this file except in compliance with the License.
36
+ You may obtain a copy of the License at
37
+
38
+ http://www.apache.org/licenses/LICENSE-2.0
39
+
40
+ Unless required by applicable law or agreed to in writing, software
41
+ distributed under the License is distributed on an "AS IS" BASIS,
42
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
43
+ See the License for the specific language governing permissions and
44
+ limitations under the License.
45
+ -->
46
+
47
+ # STAC API Protocol
48
+
49
+ [![PyPI - Version](https://img.shields.io/pypi/v/stac-api-protocol.svg)](https://pypi.org/project/stac-api-protocol)
50
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/stac-api-protocol.svg)](https://pypi.org/project/stac-api-protocol)
51
+ [![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/terradue/stac-api-protocol/package.yaml?branch=develop&event=push&label=build&logo=githubactions)](https://github.com/terradue/stac-api-protocol/actions/workflows/package.yaml?query=branch%3Adevelop)
52
+ [![Code coverage](https://img.shields.io/codecov/c/github/terradue/stac-api-protocol/develop?logo=codecov)](https://app.codecov.io/gh/terradue/stac-api-protocol/tree/develop)
53
+
54
+ A Python FastAPI HTTP adapter for STAC API Core, Item Search, Features and Collections.
55
+
56
+ ## Project conventions
57
+
58
+ This project is templated a Hatch-based Python package with:
59
+
60
+ - Apache-2.0 license
61
+ - Keep a Changelog-compatible `CHANGELOG.md`
62
+ - Diátaxis documentation under `docs/`
63
+ - top-level `mkdocs.yaml`
64
+ - Taskfile integration with `Terradue/taskfile-utils`
65
+ - GitHub Actions CI
66
+
67
+ ## Documentation
68
+
69
+ Project documentation is published at:
70
+
71
+ ## Contribute
72
+
73
+ Submit a [Github issue](/issues) if you have comments or suggestions.
74
+
75
+ ### Local quality checks
76
+
77
+ Install [Hatch](https://hatch.pypa.io/) and [Taskfiles](https://taskfile.dev/docs/guide) then install the Git hook:
78
+
79
+ ```console
80
+ task quality:pre-commit:install
81
+ ```
82
+
83
+ Every commit runs Ruff (including the configured McCabe complexity limit),
84
+ Ruff formatting, strict mypy checks, and the pytest suite.
85
+
86
+ Run the complete hook explicitly with:
87
+
88
+ ```console
89
+ task quality:pre-commit:run
90
+ ```
91
+
92
+ ## License
93
+
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)
@@ -0,0 +1,11 @@
1
+ stac_api_protocol/__about__.py,sha256=2v5T2d6jTvE2LtfjByfeX25zCl-BFUhzoaY_OLPDtL4,642
2
+ stac_api_protocol/__init__.py,sha256=xx1XrBGtAMEOLxd6dnDtYKkZsZ61bG7Vx-9b1O6uB9s,747
3
+ stac_api_protocol/main.py,sha256=057ory2QVO7XrZD0Zjvq1ujdme0AdbfZ-f4DyHREN5o,14063
4
+ stac_api_protocol/models.py,sha256=WKu5TBHwoxkTV4FtQ-TQMmQKcB5bWVr82Zg_f76wTnk,5471
5
+ stac_api_protocol/plugin_loader.py,sha256=PDc1Wh25TduWCheJXAxKyZbJZgCNkLTkCgEJuqRj6Do,1432
6
+ stac_api_protocol/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
7
+ stac_api_protocol/stac_service.py,sha256=EjCkP0Y-BxdBHF_pFPifC2E2-MhfsI0gLGSj5-CzWDY,4325
8
+ stac_api_protocol-0.1.0.dist-info/METADATA,sha256=NEALk6cYbBNuUfSTt4R_qZwu95CFJxcXgrz0VhjlYjQ,3751
9
+ stac_api_protocol-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ stac_api_protocol-0.1.0.dist-info/licenses/LICENSE,sha256=ncoZH9Riydi4edtpNYeB7IymLIEpnL1SQB0fM4A8NHA,11343
11
+ stac_api_protocol-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Terradue
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.