### MyCustomExtension Example Source: https://context7.com/stac-utils/stac-fastapi/llms.txt This example demonstrates how to create a custom extension that adds a GET /custom endpoint and supports a `custom_param` query parameter. ```APIDOC ## GET /custom ### Description An example custom endpoint that accepts a `custom_param` and returns a message. ### Method GET ### Endpoint /custom ### Parameters #### Query Parameters - **custom_param** (string) - Optional - A custom parameter for the endpoint. ### Request Example ```bash curl "http://localhost:8000/custom?custom_param=hello" ``` ### Response #### Success Response (200) - **message** (string) - A message indicating the value of `custom_param`. #### Response Example ```json { "message": "custom_param=hello" } ``` ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/stac-utils/stac-fastapi/blob/main/CONTRIBUTING.md Clone the repository and install development dependencies using uv. ```bash git clone https://github.com/stac-utils/stac-fastapi.git cd stac-fastapi uv sync --dev ``` -------------------------------- ### Example Collection Search API Calls Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Illustrates how to query collections using GET requests with spatial, temporal, and text filters. ```bash # curl "http://localhost:8000/collections?bbox=-10,35,30,60&datetime=2023-01-01/.." # curl "http://localhost:8000/collections?q=optical" ``` -------------------------------- ### GET Search with Free Text Query Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Example GET request to the search endpoint using the `q` parameter for a free-text search. ```bash # GET search with free text # curl "http://localhost:8000/search?q=sentinel+europe+2023" ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/stac-utils/stac-fastapi/blob/main/CONTRIBUTING.md Install pre-commit hooks to ensure code quality and consistency before committing. ```bash uv run pre-commit install ``` -------------------------------- ### Install stac-fastapi Source: https://github.com/stac-utils/stac-fastapi/blob/main/docs/src/index.md Install the stac-fastapi package using pip. ```bash pip install stac-fastapi ``` -------------------------------- ### Install Development Dependencies with uv Source: https://github.com/stac-utils/stac-fastapi/blob/main/README.md Use uv to synchronize development dependencies for the project. Ensure uv is installed separately. ```shell uv sync --dev ``` -------------------------------- ### Install stac-fastapi from PyPI Source: https://github.com/stac-utils/stac-fastapi/blob/main/README.md Install the core stac-fastapi packages and a specific backend like pgstac from PyPI using pip. ```shell python -m pip install stac-fastapi.types stac-fastapi.api stac-fastapi.extensions ``` ```shell python -m pip install stac-fastapi.pgstac ``` -------------------------------- ### GET Search with Sortby Parameter Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Example of a GET request to the search endpoint with `sortby` parameter for ascending and descending order. ```bash # GET with sortby (field prefix: + ascending, - descending) # curl "http://localhost:8000/search?sortby=-properties.datetime,+id" ``` -------------------------------- ### Example Aggregation API Calls Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Demonstrates how to call the aggregation endpoints using curl. ```bash # curl http://localhost:8000/aggregations # curl http://localhost:8000/collections/sentinel-2-l2a/aggregations # curl "http://localhost:8000/aggregate?collections=sentinel-2-l2a&datetime=2023-01-01/.." ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/stac-utils/stac-fastapi/blob/main/docs/src/contributing.md Install pre-commit hooks to ensure code quality checks are run before committing. You can also run pre-commit manually on all files. ```bash uv run pre-commit install # If needed, you can run pre-commit script manually uv run pre-commit run --all-files ``` -------------------------------- ### Query STAC API with CQL2-Text Filter Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Example of a GET request to the search endpoint using a CQL2-Text filter for cloud cover less than or equal to 20. ```bash # GET search with CQL2-Text filter # curl "http://localhost:8000/search?filter=eo%3Acloud_cover+%3C%3D+20&filter-lang=cql2-text" ``` -------------------------------- ### STAC FastAPI Core REST Endpoints (curl examples) Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Examples of how to interact with the core STAC API endpoints using `curl` for landing page, conformance, collections, items, and search. ```bash # Landing page curl http://localhost:8000/ ``` ```bash # Conformance classes curl http://localhost:8000/conformance ``` ```bash # List all collections curl http://localhost:8000/collections ``` ```bash # Get a single collection curl http://localhost:8000/collections/sentinel-2-l2a ``` ```bash # List items in a collection (with bbox filter and limit) curl "http://localhost:8000/collections/sentinel-2-l2a/items?bbox=-10,35,30,60&limit=5" ``` ```bash # Get a single item curl http://localhost:8000/collections/sentinel-2-l2a/items/S2A_MSIL2A_20230601T100031 ``` ```bash # GET search curl "http://localhost:8000/search?collections=sentinel-2-l2a&bbox=-10,35,30,60&datetime=2023-01-01T00:00:00Z/2023-06-01T00:00:00Z&limit=10" ``` ```bash # POST search curl -X POST http://localhost:8000/search \ -H "Content-Type: application/json" \ -d '{ "collections": ["sentinel-2-l2a"], "bbox": [-10, 35, 30, 60], "datetime": "2023-01-01T00:00:00Z/2023-06-01T00:00:00Z", "limit": 10, "sortby": [{"field": "properties.datetime", "direction": "desc"}] }' ``` -------------------------------- ### Minimal STAC API with In-Memory Backend Source: https://context7.com/stac-utils/stac-fastapi/llms.txt This example demonstrates setting up a minimal STAC API using an in-memory backend client. It configures API settings, extensions, and custom search request models. Replace `MyClient` with your actual database client implementation for production use. ```python import uvicorn from stac_fastapi.api.app import StacApi from stac_fastapi.api.models import create_get_request_model, create_post_request_model from stac_fastapi.types.config import ApiSettings from stac_fastapi.types.core import BaseCoreClient from stac_fastapi.types.search import BaseSearchPostRequest from stac_fastapi.extensions.core import ( FilterExtension, SortExtension, FieldsExtension, TransactionExtension, ) from stac_fastapi.extensions.core.transaction.client import BaseTransactionsClient # Minimal in-memory backend – replace with real DB calls class MyClient(BaseCoreClient): def post_search(self, search_request: BaseSearchPostRequest, **kwargs): return {"type": "FeatureCollection", "features": []} def get_search(self, collections=None, ids=None, bbox=None, intersects=None, datetime=None, limit=10, **kwargs): return {"type": "FeatureCollection", "features": []} def get_item(self, item_id: str, collection_id: str, **kwargs): raise NotFoundError(f"{item_id} not found") def all_collections(self, **kwargs): return {"collections": [], "links": []} def get_collection(self, collection_id: str, **kwargs): raise NotFoundError(f"{collection_id} not found") def item_collection(self, collection_id, bbox=None, datetime=None, limit=10, token=None, **kwargs): return {"type": "FeatureCollection", "features": []} settings = ApiSettings( stac_fastapi_title="My STAC API", stac_fastapi_version="1.0.0", stac_fastapi_description="A demo STAC API", enable_response_models=True, # validate output against stac-pydantic models enable_direct_response=False, # set True to skip FastAPI serialization for speed ) extensions = [SortExtension(), FieldsExtension(), FilterExtension()] # Build GET/POST search request models that merge extension parameters search_get_model = create_get_request_model(extensions) search_post_model = create_post_request_model(extensions) api = StacApi( settings=settings, client=MyClient(), extensions=extensions, search_get_request_model=search_get_model, search_post_request_model=search_post_model, ) # api.app is the ASGI app if __name__ == "__main__": uvicorn.run(api.app, host=settings.app_host, port=settings.app_port) ``` -------------------------------- ### Example Bulk Item Insertion Response Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Shows the expected response after a successful bulk item insertion request. ```text # Response: "Successfully inserted 2 items" ``` -------------------------------- ### POST Search with Basic Free Text Query Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Example POST request to the search endpoint using the `q` parameter for a basic free-text search. ```bash # POST search with free text (basic: single string) curl -X POST http://localhost:8000/search \ -H "Content-Type: application/json" \ -d '{"q": "cloud free imagery europe", "limit": 10}' ``` -------------------------------- ### POST Search with Advanced Free Text Query Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Example POST request using the advanced free-text extension where `q` is a list of terms for AND semantics. ```bash # Advanced extension: q is a list of terms (AND semantics) # -d '{"q": ["sentinel-2", "cloud-free"], "limit": 10}' ``` -------------------------------- ### Example Bulk Item Insertion Request Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Demonstrates a POST request to ingest multiple STAC items in bulk, specifying the operation method (e.g., 'upsert'). ```bash # POST bulk items curl -X POST http://localhost:8000/collections/my-collection/bulk_items \ -H "Content-Type: application/json" \ -d '{ "items": { "item-001": {"type": "Feature", "stac_version": "1.0.0", "id": "item-001", "geometry": {"type": "Point", "coordinates": [10, 50]}, "bbox": [9, 49, 11, 51], "properties": {"datetime": "2023-06-01T00:00:00Z"}, "links": [], "assets": {}, "collection": "my-collection"}, "item-002": {"type": "Feature", "stac_version": "1.0.0", "id": "item-002", "geometry": {"type": "Point", "coordinates": [20, 45]}, "bbox": [19, 44, 21, 46], "properties": {"datetime": "2023-06-02T00:00:00Z"}, "links": [], "assets": {}, "collection": "my-collection"} }, "method": "upsert" }' ``` -------------------------------- ### Example cURL Commands for Transaction Extension Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Demonstrates how to use cURL to interact with the STAC API endpoints enabled by the `TransactionExtension` for managing collections and items. ```shell # POST /collections (create collection) curl -X POST http://localhost:8000/collections \ -H "Content-Type: application/json" \ -d '{"type":"Collection","id":"my-col","description":"Demo","license":"proprietary", "extent":{"spatial":{"bbox":[[-180,-90,180,90]]}, "temporal":{"interval":[[\"2020-01-01T00:00:00Z\",null]]}},"links":[]}' ``` ```shell # PUT /collections/my-col/items/item-01 (full update) # PATCH /collections/my-col/items/item-01 (partial update with merge-patch or JSON Patch) # DELETE /collections/my-col/items/item-01 ``` -------------------------------- ### POST Search with Sortby Parameter Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Example of a POST request to the search endpoint with a structured `sortby` array for ordering results. ```bash # POST with sortby curl -X POST http://localhost:8000/search \ -H "Content-Type: application/json" \ -d '{ "collections": ["landsat-8-l1tp"], "sortby": [ {"field": "properties.datetime", "direction": "desc"}, {"field": "id", "direction": "asc"} ] }' ``` -------------------------------- ### Bump Version with bump-my-version Source: https://github.com/stac-utils/stac-fastapi/blob/main/RELEASING.md Use the bump-my-version CLI to update the project's version number. Ensure you have the necessary tools installed and configured. ```bash uv run --with bump-my-version bump bump-my-version --new-version 3.1.0 ``` -------------------------------- ### Implement AsyncBaseCoreClient Backend Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Subclass `AsyncBaseCoreClient` to define backend logic for STAC operations like searching items, getting collections, and retrieving individual items. ```python from typing import List, Optional from stac_fastapi.types.core import AsyncBaseCoreClient from stac_fastapi.types.errors import NotFoundError from stac_fastapi.types.search import BaseSearchPostRequest class PgSTACClient(AsyncBaseCoreClient): """Example async backend backed by a database connection pool (pool injected separately).""" async def post_search(self, search_request: BaseSearchPostRequest, **kwargs): # search_request exposes .collections, .ids, .bbox, .datetime, .limit, etc. results = await db.search(search_request.model_dump(exclude_none=True)) return {"type": "FeatureCollection", "features": results} async def get_search(self, collections=None, ids=None, bbox=None, intersects=None, datetime=None, limit=10, **kwargs): results = await db.search({"collections": collections, "bbox": bbox, "datetime": datetime, "limit": limit}) return {"type": "FeatureCollection", "features": results} async def get_item(self, item_id: str, collection_id: str, **kwargs): item = await db.get_item(collection_id, item_id) if not item: raise NotFoundError(f"Item {item_id} not found in {collection_id}") return item async def all_collections(self, **kwargs): cols = await db.list_collections() return {"collections": cols, "links": []} async def get_collection(self, collection_id: str, **kwargs): col = await db.get_collection(collection_id) if not col: raise NotFoundError(f"Collection {collection_id} not found") return col async def item_collection(self, collection_id, bbox=None, datetime=None, limit=10, token=None, **kwargs): items = await db.get_items(collection_id, bbox=bbox, datetime=datetime, limit=limit, token=token) return {"type": "FeatureCollection", "features": items} ``` -------------------------------- ### POST Search with Fields Inclusion/Exclusion Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Example POST request to the search endpoint using the `fields` parameter to return only specific fields. ```bash # POST search returning only id, datetime, and cloud cover curl -X POST http://localhost:8000/search \ -H "Content-Type: application/json" \ -d '{ "collections": ["sentinel-2-l2a"], "fields": { "include": ["id", "properties.datetime", "properties.eo:cloud_cover"], "exclude": ["assets", "links"] }, "limit": 5 }' ``` -------------------------------- ### Configure Collection Search Extension Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Set up the CollectionSearchExtension with optional sub-extensions like FilterExtension and FreeTextExtension. The `collections_get_request_model` must be set to the extension's GET model. ```python from stac_fastapi.extensions.core.collection_search import ( CollectionSearchExtension, CollectionSearchPostExtension, ) from stac_fastapi.extensions.core import FilterExtension, FreeTextExtension # GET-only collection search with sub-extensions col_search_ext = CollectionSearchExtension.from_extensions( extensions=[FilterExtension(), FreeTextExtension()] ) api = StacApi( settings=ApiSettings(), client=MyClient(), extensions=[col_search_ext], collections_get_request_model=col_search_ext.GET, ) ``` -------------------------------- ### Query STAC API with CQL2-JSON Filter Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Example of a POST request to the search endpoint using a CQL2-JSON filter to find items with cloud cover less than or equal to 20. ```bash # POST search with CQL2-JSON filter curl -X POST http://localhost:8000/search \ -H "Content-Type: application/json" \ -d '{ "collections": ["sentinel-2-l2a"], "filter-lang": "cql2-json", "filter": { "op": "<= ", "args": [{"property": "eo:cloud_cover"}, 20] } }' ``` -------------------------------- ### Configure Items Get Request Model for Pagination Source: https://github.com/stac-utils/stac-fastapi/blob/main/docs/src/migrations/v3.0.0.md In v3.0, the `pagination_extension` attribute is removed. Manually create the request model for the `/collections/{collection_id}/items` endpoint using `create_request_model` and `TokenPaginationExtension().GET`. ```python from stac_fastapi.api.models.links import ItemCollectionUri from stac_fastapi.extensions.core import TokenPaginationExtension from stac_fastapi.api.app import StacApi from stac_fastapi.api.models.search import create_request_model # before # stac=StacApi( # pagination_extension=TokenPaginationExtension, # extension=[TokenPaginationExtension] # ) # now items_get_request_model = create_request_model( "ItemCollectionURI", base_model=ItemCollectionUri, mixins=[TokenPaginationExtension().GET], ) stac=StacApi( extension=[TokenPaginationExtension], items_get_request_model=items_get_request_model, ) ``` -------------------------------- ### Add Token and Offset Pagination to STAC API Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Use PaginationExtension for token-based pagination and OffsetPaginationExtension for offset-based pagination. These extensions add query parameters for GET requests and fields for POST requests. ```python from stac_fastapi.extensions.core.pagination import ( PaginationExtension, OffsetPaginationExtension, ) extensions = [PaginationExtension()] api = StacApi( settings=ApiSettings(), client=MyClient(), extensions=extensions, search_get_request_model=create_get_request_model(extensions), search_post_request_model=create_post_request_model(extensions), ) # GET search with token pagination # curl "http://localhost:8000/search?limit=20&token=eyJuZXh0IjogMjB9" # POST search with token curl -X POST http://localhost:8000/search \ -H "Content-Type: application/json" \ -d '{"collections": ["sentinel-2-l2a"], "limit": 20, "token": "eyJuZXh0IjogMjB9"}' ``` -------------------------------- ### Serve Documentation with Hot-reloading Source: https://github.com/stac-utils/stac-fastapi/blob/main/CONTRIBUTING.md Serve the documentation locally with live reloading for development. ```bash uv run --group docs mkdocs serve -f docs/mkdocs.yml --livereload ``` -------------------------------- ### Build Documentation Source: https://github.com/stac-utils/stac-fastapi/blob/main/CONTRIBUTING.md Build the project documentation using mkdocs. ```bash git clone https://github.com/stac-utils/stac-fastapi.git cd stac-fastapi # Build docs uv run --group docs mkdocs build -f docs/mkdocs.yml ``` -------------------------------- ### GET Search Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Performs a search for STAC items based on various criteria using GET parameters. ```APIDOC ## GET /search ### Description Performs a search for STAC items using GET parameters. ### Method GET ### Endpoint /search #### Query Parameters - **collections** (array) - Optional - Filter by collection IDs. - **bbox** (array) - Optional - Filter by bounding box. - **datetime** (string) - Optional - Filter by date/time range. - **limit** (integer) - Optional - Maximum number of items to return. ``` -------------------------------- ### Deploy Documentation Source: https://github.com/stac-utils/stac-fastapi/blob/main/CONTRIBUTING.md Manually deploy the documentation to GitHub Pages. Note: GitHub Actions typically handles this automatically. ```bash # deploy uv run --group docs mkdocs gh-deploy -f docs/mkdocs.yml ``` -------------------------------- ### Define Base Search GET Request Model Source: https://github.com/stac-utils/stac-fastapi/blob/main/docs/src/migrations/v3.0.0.md Use `stac_fastapi.types.search.APIRequest` as the base class for GET request models. Define type hints using `Annotated[{type}, fastapi.Query()]` for attributes. ```python import attr from typing import Optional, List from stac_fastapi.types.search import APIRequest from stac_fastapi.types.stac import BBox from fastapi import Query def _collection_converter(val: Optional[str]) -> Optional[List[str]]: return str2list(val) def _ids_converter(val: Optional[str]) -> Optional[List[str]]: return str2list(val) def _bbox_converter(val: Optional[List[NumType]]) -> Optional[BBox]: return BBox(val) def _datetime_converter(val: Optional[str]) -> Optional[DateTimeType]: return parse_datetime(val) @attr.s class BaseSearchGetRequest(APIRequest): """Base arguments for GET Request.""" collections: Optional[List[str]] = attr.ib(default=None, converter=_collection_converter) ids: Optional[List[str]] = attr.ib(default=None, converter=_ids_converter) bbox: Optional[BBox] = attr.ib(default=None, converter=_bbox_converter) intersects: Annotated[Optional[str], Query()] = attr.ib(default=None) datetime: Optional[DateTimeType] = attr.ib( default=None, converter=_datetime_converter ) limit: Annotated[Optional[int], Query()] = attr.ib(default=10) ``` -------------------------------- ### Test Datetime String Type in GET Request Source: https://github.com/stac-utils/stac-fastapi/blob/main/docs/src/migrations/v4.0.0.md Verify that the 'datetime' parameter in GET requests is now treated as a string, aligning with stac-pydantic's validation. This test demonstrates the behavior before and after the change. ```python from starlette.testclient import TestClient from stac_fastapi.api.app import StacApi from stac_fastapi.types.config import ApiSettings from stac_fastapi.types.core import BaseCoreClient class DummyCoreClient(BaseCoreClient): def all_collections(self, *args, **kwargs): raise NotImplementedError def get_collection(self, *args, **kwargs): raise NotImplementedError def get_item(self, *args, **kwargs): raise NotImplementedError def get_search(self, *args, datetime = None, **kwargs): # Return True if datetime is a string return isinstance(datetime, str) def post_search(self, *args, **kwargs): raise NotImplementedError def item_collection(self, *args, **kwargs): raise NotImplementedError api = StacApi( settings=ApiSettings(enable_response_models=False), client=DummyCoreClient(), extensions=[], ) # before with TestClient(api.app) as client: response = client.get( "/search", params={ "datetime": "2020-01-01T00:00:00.00001Z", }, ) assert response.json() == False # now with TestClient(api.app) as client: response = client.get( "/search", params={ "datetime": "2020-01-01T00:00:00.00001Z", }, ) assert response.json() == True ``` -------------------------------- ### APIRequest - GET Request Model Source: https://github.com/stac-utils/stac-fastapi/blob/main/docs/src/migrations/v3.0.0.md In v3.0.0, GET endpoints are configured with `stac_fastapi.types.search.APIRequest`. Type hints for attributes should use `Annotated[{type}, fastapi.Query()]`. Converters require type hints within the converter itself. ```APIDOC ## APIRequest - GET Request Model Most of the **GET** endpoints are configured with `stac_fastapi.types.search.APIRequest` base class. e.g the BaseSearchGetRequest, default for the `GET - /search` endpoint: ```python @attr.s class BaseSearchGetRequest(APIRequest): """Base arguments for GET Request.""" collections: Optional[List[str]] = attr.ib(default=None, converter=_collection_converter) ids: Optional[List[str]] = attr.ib(default=None, converter=_ids_converter) bbox: Optional[BBox] = attr.ib(default=None, converter=_bbox_converter) intersects: Annotated[Optional[str], Query()] = attr.ib(default=None) datetime: Optional[DateTimeType] = attr.ib( default=None, converter=_datetime_converter ) limit: Annotated[Optional[int], Query()] = attr.ib(default=10) ``` We use [*python attrs*](https://www.attrs.org/en/stable/) to construct those classes. **Type Hint** for each attribute is important and should be defined using `Annotated[{type}, fastapi.Query()]` form. ```python @attr.s class SomeRequest(APIRequest): user_number: Annotated[Optional[int], Query(alias="user-number")] = attr.ib(default=None) ``` Note: when an attribute has a `converter` (e.g `_ids_converter`), the **Type Hint** should be defined directly in the converter: ```python def _ids_converter( val: Annotated[ Optional[str], Query( description="Array of Item ids to return.", ), ] = None, ) -> Optional[List[str]]: return str2list(val) @attr.s class BaseSearchGetRequest(APIRequest): """Base arguments for GET Request.""" ids: Optional[List[str]] = attr.ib(default=None, converter=_ids_converter) ``` ``` -------------------------------- ### Get Single Collection Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Retrieves details for a specific STAC collection. ```APIDOC ## GET /collections/{collection_id} ### Description Retrieves details for a specific STAC collection. ### Method GET ### Endpoint /collections/{collection_id} #### Path Parameters - **collection_id** (string) - Required - The ID of the collection to retrieve. ``` -------------------------------- ### BaseSearchGetRequest / BaseSearchPostRequest Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Models for validating search request parameters for GET and POST requests. ```APIDOC ## `BaseSearchGetRequest` / `BaseSearchPostRequest` — Search Request Models `BaseSearchGetRequest` is an `attrs`-based class used for GET requests; `BaseSearchPostRequest` extends `stac_pydantic.api.Search` for POST bodies. Both handle validation of `bbox`, `datetime`, `collections`, `ids`, and `limit`. ```python from stac_fastapi.types.search import BaseSearchGetRequest, BaseSearchPostRequest ``` ``` -------------------------------- ### Initialize Benchmark Data Rendering Source: https://github.com/stac-utils/stac-fastapi/blob/main/docs/src/benchmarks.html Initializes the benchmark data by collecting results per test case and rendering the page header and footer. It prepares data points for charting. ```javascript 'use strict'; (function() { // Colors from https://github.com/github/linguist/blob/master/lib/linguist/languages.yml const toolColors = { cargo: '#dea584', go: '#00add8', benchmarkjs: '#f1e05a', benchmarkluau: '#000080', pytest: '#3572a5', googlecpp: '#f34b7d', catch2: '#f34b7d', julia: '#a270ba', jmh: '#b07219', benchmarkdotnet: '#178600', customBiggerIsBetter: '#38ff38', customSmallerIsBetter: '#ff3838', _: '#333333' }; function init(data) { function collectBenchesPerTestCase(entries) { const map = new Map(); for (const entry of entries) { const {commit, date, tool, benches} = entry; for (const bench of benches) { const result = { commit, date, tool, bench }; const arr = map.get(bench.name); if (arr === undefined) { map.set(bench.name, [result]); } else { arr.push(result); } } } return map; } // Render header document.getElementById('last-update').textContent = new Date(data.lastUpdate).toString(); const repoLink = document.getElementById('repository-link'); repoLink.href = data.repoUrl; repoLink.textContent = data.repoUrl; // Render footer document.getElementById('dl-button').onclick = () => { const dataUrl = 'data:,' + JSON.stringify(data, null, 2); const a = document.createElement('a'); a.href = dataUrl; a.download = 'benchmark_data.json'; a.click(); }; // Prepare data points for charts return Object.keys(data.entries).map(name => ({ name, dataSet: collectBenchesPerTestCase(data.entries[name]), })); } function renderAllChars(dataSets) { function renderGraph(parent, name, dataset) { const canvas = document.createElement('canvas'); canvas.className = 'benchmark-chart'; parent.appendChild(canvas); const color = toolColors[dataset.length > 0 ? dataset[0].tool : '_']; const data = { labels: dataset.map(d => d.commit.id.slice(0, 7)), datasets: [ { label: name, data: dataset.map(d => d.bench.value), borderColor: color, backgroundColor: color + '60', // Add alpha for #rrggbbaa }, ], }; const options = { scales: { xAxes: [ { scaleLabel: { display: true, labelString: 'commit', }, } ], yAxes: [ { scaleLabel: { display: true, labelString: dataset.length > 0 ? dataset[0].bench.unit : '', }, ticks: { beginAtZero: true, } } ], }, tooltips: { callbacks: { afterTitle: items => { const {index} = items[0]; const data = dataset[index]; return '\n' + data.commit.message + '\n\n' + data.commit.timestamp + ' committed by @' + data.commit.committer.username + '\n'; }, label: item => { let label = item.value; const { range, unit } = dataset[item.index].bench; label += ' ' + unit; if (range) { label += ' (' + range + ')'; } return label; }, afterLabel: item => { const { extra } = dataset[item.index].bench; return extra ? '\n' + extra : ''; } } }, onClick: (_mouseEvent, activeElems) => { if (activeElems.length === 0) { return; } // XXX: Undocumented. How can we know the index? const index = activeElems[0]._index; const url = dataset[index].commit.url; window.open(url, '_blank'); }, }; new Chart(canvas, { type: 'line', data, options }); } function renderBenchSet(name, benchSet, main) { const setElem = document.createElement('div'); setElem.className = 'benchmark-set'; main.appendChild(setElem); const nameElem = document.createElement('h1'); nameElem.className = 'benchmark-title'; nameElem.textContent = name; setElem.appendChild(nameElem); const graphsElem = document.createElement('div'); graphsElem.className = 'benchmark-graphs'; setElem.appendChild(graphsElem); for (const [benchName, benches] of benchSet.entries()) { renderGraph(graphsElem, benchName, benches) } } const main = document.getElementById('main'); for (c ``` -------------------------------- ### Get Single Item Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Retrieves details for a specific STAC item within a collection. ```APIDOC ## GET /collections/{collection_id}/items/{item_id} ### Description Retrieves details for a specific STAC item within a collection. ### Method GET ### Endpoint /collections/{collection_id}/items/{item_id} #### Path Parameters - **collection_id** (string) - Required - The ID of the collection. - **item_id** (string) - Required - The ID of the item to retrieve. ``` -------------------------------- ### Configure StacApi Middlewares Source: https://github.com/stac-utils/stac-fastapi/blob/main/docs/src/migrations/v3.0.0.md Demonstrates the updated syntax for configuring middlewares in StacApi. Previously, middleware classes were passed directly; now, `starlette.middleware.Middleware` instances are used, allowing for dynamic configuration and passing options. ```python class myMiddleware(mainMiddleware): option1 = option1 option2 = option2 stac = StacApi( middlewares=[ myMiddleware, ] ) ``` ```python stac = StacApi( middlewares=[ Middleware(myMiddleware, option1, option2), ] ) ``` -------------------------------- ### SortExtension Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Adds a `sortby` parameter to the `/search` endpoint (both GET and POST) for ordering results. No additional client method is required. ```APIDOC ## `SortExtension` — Result Ordering Adds a `sortby` parameter to `/search` (GET and POST). No additional client method is required; the backend reads `sortby` from the search request object. ### GET with sortby (field prefix: `+` ascending, `-` descending) ```bash curl "http://localhost:8000/search?sortby=-properties.datetime,+id" ``` ### POST with sortby ```bash curl -X POST http://localhost:8000/search \ -H "Content-Type: application/json" \ -d '{ "collections": ["landsat-8-l1tp"], "sortby": [ {"field": "properties.datetime", "direction": "desc"}, {"field": "id", "direction": "asc"} ] }' ``` ``` -------------------------------- ### Implement Free-Text Search with FreeTextExtension Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Add a `q` parameter for basic free-text search to the API using `FreeTextExtension`. Ensure `search_get_request_model` and `search_post_request_model` are configured. ```python from stac_fastapi.extensions.core import FreeTextExtension from stac_fastapi.extensions.core.free_text import FreeTextAdvancedExtension extensions = [FreeTextExtension()] api = StacApi( settings=ApiSettings(), client=MyClient(), extensions=extensions, search_get_request_model=create_get_request_model(extensions), search_post_request_model=create_post_request_model(extensions), ) ``` -------------------------------- ### Implement Result Ordering with SortExtension Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Integrate the `SortExtension` to enable sorting of search results. No additional client methods are required. ```python from stac_fastapi.extensions.core import SortExtension extensions = [SortExtension()] api = StacApi( settings=ApiSettings(), client=MyClient(), extensions=extensions, search_get_request_model=create_get_request_model(extensions), search_post_request_model=create_post_request_model(extensions), ) ``` -------------------------------- ### Implement Aggregation Client Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Extend AsyncBaseAggregationClient to define custom aggregation logic. Requires defining `get_aggregations` and `aggregate` methods. ```python from stac_fastapi.extensions.core.aggregation import AggregationExtension from stac_fastapi.extensions.core.aggregation.client import AsyncBaseAggregationClient class MyAggregationClient(AsyncBaseAggregationClient): async def get_aggregations(self, collection_id=None, **kwargs): return { "aggregations": [ {"name": "total_count", "data_type": "integer"}, {"name": "datetime_frequency", "data_type": "frequency_distribution", "bucket_count_limit": 100}, {"name": "platform_frequency", "data_type": "frequency_distribution"}, ] } async def aggregate(self, collection_id=None, **kwargs): return { "type": "AggregationCollection", "aggregations": [ {"name": "total_count", "data_type": "integer", "value": 42503}, {"name": "platform_frequency", "data_type": "frequency_distribution", "buckets": [ {"key": "sentinel-2a", "data_type": "integer", "frequency": 28000}, {"key": "sentinel-2b", "data_type": "integer", "frequency": 14503}, ]}, ], } ``` -------------------------------- ### Configure STAC FastAPI Settings Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Set up API title, version, host, port, and enable/disable features like response validation and direct response. ```python settings = ApiSettings( stac_fastapi_title="Earth Observation API", stac_fastapi_version="2.3.0", stac_fastapi_landing_id="eo-stac-api", stac_fastapi_description="Global EO data catalog.", app_host="0.0.0.0", app_port=8080, enable_response_models=False, # skip pydantic output validation (faster) enable_direct_response=True, # return Response objects directly (fastest) openapi_url="/api", docs_url="/api.html", root_path="/v1", # useful behind a reverse proxy ) # After StacApi is constructed, settings are registered globally: # Settings.get() returns the active ApiSettings from anywhere in the app. active = Settings.get() print(active.stac_fastapi_title) # "Earth Observation API" ``` -------------------------------- ### CollectionSearchExtension / CollectionSearchPostExtension Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Enhances `GET /collections` with spatial/temporal/text filter parameters. The POST variant adds `POST /collections` for a JSON body search. ```APIDOC ## `CollectionSearchExtension` / `CollectionSearchPostExtension` — Collection-Level Search Enhances `GET /collections` with spatial/temporal/text filter parameters. The POST variant adds `POST /collections` for a JSON body search. ### Endpoints - **GET /collections** - Description: Retrieves collections with optional spatial, temporal, and text filters. - Query Parameters: - `bbox` (string) - Optional - Bounding box filter. - `datetime` (string) - Optional - Temporal filter. - `q` (string) - Optional - Free-text search query. - Example: `curl "http://localhost:8000/collections?bbox=-10,35,30,60&datetime=2023-01-01/.."` - Example: `curl "http://localhost:8000/collections?q=optical"` - **POST /collections** - Description: Retrieves collections using a JSON request body for filtering. - Request Body: - `bbox` (object) - Optional - Bounding box filter. - `datetime` (string) - Optional - Temporal filter. - `q` (string) - Optional - Free-text search query. - Example: (Refer to `stac_fastapi.extensions.core.collection_search` for request body structure) ``` -------------------------------- ### STAC FastAPI Configuration with ApiSettings Source: https://context7.com/stac-utils/stac-fastapi/llms.txt Demonstrates how to configure STAC FastAPI settings using `ApiSettings`, a Pydantic `BaseSettings` subclass. Settings can be overridden via environment variables or a `.env` file. ```python from stac_fastapi.types.config import ApiSettings, Settings # Configured via environment variables: # STAC_FASTAPI_TITLE, STAC_FASTAPI_VERSION, STAC_FASTAPI_DESCRIPTION # STAC_FASTAPI_LANDING_ID, APP_HOST, APP_PORT # ENABLE_RESPONSE_MODELS, ENABLE_DIRECT_RESPONSE ```