Skip to content

API Reference

tellus_traveler.api

Functions corresponding to Tellus Traveler API endpoints.

dataset(id)

Gets a dataset by ID.

https://www.tellusxdp.com/docs/travelers/#/データセット/get_datasets__dataset_id__

Parameters:

Name Type Description Default
id str

Dataset ID.

required

Returns:

Type Description
dict[str, Any]

A dataset dictionary.

Source code in src/tellus_traveler/api/_datasets.py
def dataset(id: str) -> dict[str, Any]:
    """Gets a dataset by ID.

    <https://www.tellusxdp.com/docs/travelers/#/データセット/get_datasets__dataset_id__>

    Args:
        id: Dataset ID.

    Returns:
        A dataset dictionary.
    """
    return http_client.get(f"/datasets/{id}/")

dataset_manual_url(id)

Gets a dataset manual URL by ID.

https://www.tellusxdp.com/docs/travelers/#/データセットメディア/get_datasets__dataset_id__manual_

Parameters:

Name Type Description Default
id str

Dataset ID.

required

Returns:

Type Description
str

A dataset manual URL.

Source code in src/tellus_traveler/api/_datasets.py
def dataset_manual_url(id: str) -> str:
    """Gets a dataset manual URL by ID.

    <https://www.tellusxdp.com/docs/travelers/#/データセットメディア/get_datasets__dataset_id__manual_>

    Args:
        id: Dataset ID.

    Returns:
        A dataset manual URL.
    """
    return http_client.get(f"/datasets/{id}/manual/")

dataset_terms_url(id)

Gets a dataset terms of use URL by ID.

https://www.tellusxdp.com/docs/travelers/#/データセットメディア/get_datasets__dataset_id__terms_of_use_

Parameters:

Name Type Description Default
id str

Dataset ID.

required

Returns:

Type Description
str

A dataset terms of use URL.

Source code in src/tellus_traveler/api/_datasets.py
def dataset_terms_url(id: str) -> str:
    """Gets a dataset terms of use URL by ID.

    <https://www.tellusxdp.com/docs/travelers/#/データセットメディア/get_datasets__dataset_id__terms_of_use_>

    Args:
        id: Dataset ID.

    Returns:
        A dataset terms of use URL.
    """
    return http_client.get(f"/datasets/{id}/terms-of-use/")

datasets(is_order_required=None, has_order=None)

Gets a list of datasets with automatic pagination.

https://www.tellusxdp.com/docs/travelers/#/データセット/get_datasets_

Parameters:

Name Type Description Default
is_order_required bool | None

Whether orders are required to download files.

None
has_order bool | None

Whether active orders exists.

None

Returns:

Type Description
list[dict[str, Any]]

A list of dataset dictionaries.

Source code in src/tellus_traveler/api/_datasets.py
def datasets(
    is_order_required: bool | None = None, has_order: bool | None = None
) -> list[dict[str, Any]]:
    """Gets a list of datasets with automatic pagination.

    <https://www.tellusxdp.com/docs/travelers/#/データセット/get_datasets_>

    Args:
        is_order_required: Whether orders are required to download files.
        has_order: Whether active orders exists.

    Returns:
        A list of dataset dictionaries.
    """

    def get_all_pages(url: str) -> list[dict[str, Any]]:
        response = http_client.get(url)
        if response.get("next"):
            return response["results"] + get_all_pages(response["next"])
        else:
            return response["results"]

    response = http_client.get(
        "/datasets/", is_order_required=is_order_required, has_order=has_order
    )

    if response.get("next"):
        return response["results"] + get_all_pages(response["next"])
    else:
        return response["results"]

scene(dataset_id, scene_id)

Get a scene info.

https://www.tellusxdp.com/docs/travelers/#/シーン/get_datasets__dataset_id__data__data_id__

Parameters:

Name Type Description Default
dataset_id str

Dataset ID.

required
scene_id str

Scene ID.

required

Returns:

Type Description
Scene

A Scene instance.

Source code in src/tellus_traveler/api/_scenes.py
def scene(dataset_id: str, scene_id: str) -> Scene:
    """Get a scene info.

    <https://www.tellusxdp.com/docs/travelers/#/シーン/get_datasets__dataset_id__data__data_id__>

    Args:
        dataset_id: Dataset ID.
        scene_id: Scene ID.

    Returns:
        A `Scene` instance.
    """
    response = http_client.get(f"/datasets/{dataset_id}/data/{scene_id}/")
    return Scene(response)

scene_file_url(dataset_id, scene_id, file_id)

Get a download URL of a file.

https://www.tellusxdp.com/docs/travelers/#/ファイル/post_datasets__dataset_id__data__data_id__files__file_id__download_url_

Parameters:

Name Type Description Default
dataset_id str

Dataset ID.

required
scene_id str

Scene ID.

required
file_id int

File ID.

required

Returns:

Type Description
str

A download URL of the file.

Source code in src/tellus_traveler/api/_files.py
def scene_file_url(dataset_id: str, scene_id: str, file_id: int) -> str:
    """Get a download URL of a file.

    <https://www.tellusxdp.com/docs/travelers/#/ファイル/post_datasets__dataset_id__data__data_id__files__file_id__download_url_>

    Args:
        dataset_id: Dataset ID.
        scene_id: Scene ID.
        file_id: File ID.

    Returns:
        A download URL of the file.
    """
    response = http_client.post(
        f"/datasets/{dataset_id}/data/{scene_id}/files/{file_id}/download-url/"
    )
    return response["download_url"]

scene_files(dataset_id, scene_id)

Get a list of file info belonging to a scene.

https://www.tellusxdp.com/docs/travelers/#/ファイル/get_datasets__dataset_id__data__data_id__files_

Parameters:

Name Type Description Default
dataset_id str

Dataset ID.

required
scene_id str

Scene ID.

required

Returns:

Type Description
list[File]

A list of File instances.

Source code in src/tellus_traveler/api/_files.py
def scene_files(dataset_id: str, scene_id: str) -> list[File]:
    """Get a list of file info belonging to a scene.

    <https://www.tellusxdp.com/docs/travelers/#/ファイル/get_datasets__dataset_id__data__data_id__files_>

    Args:
        dataset_id: Dataset ID.
        scene_id: Scene ID.

    Returns:
        A list of `File` instances.
    """
    response = http_client.get(f"/datasets/{dataset_id}/data/{scene_id}/files/")
    files = [File(dataset_id, scene_id, file) for file in response["results"]]
    return files

scene_thumbnail_url(dataset_id, scene_id, file_id)

Get a download URL of a thumbnail.

https://www.tellusxdp.com/docs/travelers/#/サムネイル/post_datasets__dataset_id__data__data_id__thumbnails__file_id__download_url_

Parameters:

Name Type Description Default
dataset_id str

Dataset ID.

required
scene_id str

Scene ID.

required
file_id int

File ID.

required

Returns:

Type Description
str

A download URL of the thumbnail.

Source code in src/tellus_traveler/api/_thumbnails.py
def scene_thumbnail_url(dataset_id: str, scene_id: str, file_id: int) -> str:
    """Get a download URL of a thumbnail.

    <https://www.tellusxdp.com/docs/travelers/#/サムネイル/post_datasets__dataset_id__data__data_id__thumbnails__file_id__download_url_>

    Args:
        dataset_id: Dataset ID.
        scene_id: Scene ID.
        file_id: File ID.

    Returns:
        A download URL of the thumbnail.
    """
    response = http_client.post(
        f"/datasets/{dataset_id}/data/{scene_id}/thumbnails/{file_id}/download-url/"
    )
    return response["download_url"]

scene_thumbnails(dataset_id, scene_id)

Get a list of thumbnail info belonging to a scene.

https://www.tellusxdp.com/docs/travelers/#/サムネイル/get_datasets__dataset_id__data__data_id__thumbnails_

Parameters:

Name Type Description Default
dataset_id str

Dataset ID.

required
scene_id str

Scene ID.

required

Returns:

Type Description
list[File]

A list of File instances.

Source code in src/tellus_traveler/api/_thumbnails.py
def scene_thumbnails(dataset_id: str, scene_id: str) -> list[File]:
    """Get a list of thumbnail info belonging to a scene.

    <https://www.tellusxdp.com/docs/travelers/#/サムネイル/get_datasets__dataset_id__data__data_id__thumbnails_>

    Args:
        dataset_id: Dataset ID.
        scene_id: Scene ID.

    Returns:
        A list of `File` instances.
    """
    response = http_client.get(f"/datasets/{dataset_id}/data/{scene_id}/thumbnails/")
    thumbs = [
        File(dataset_id, scene_id, thumb, is_thumbnail=True)
        for thumb in response["results"]
    ]
    return thumbs

search(datasets=None, bbox=None, intersects=None, start_datetime=None, end_datetime=None, query=None, is_order_required=None, only_downloadable_file=None, sort_by=None)

Search scenes.

https://www.tellusxdp.com/docs/travelers/#/シーン/post_data_search_

Parameters:

Name Type Description Default
datasets list[str] | None

Dataset IDs.

None
bbox list[float] | tuple[float, ...] | None

Bounding box of coordinates.

None
intersects dict[str, Any] | None

GeoJSON Polygon geometry.

None
start_datetime str | datetime | None

Observation start datetime.

None
end_datetime str | datetime | None

Observation end datetime.

None
query dict[str, Any] | None

Other queries for dataset properties. See the API doc for more details.

None
is_order_required bool | None

Whether orders are required to download files.

None
only_downloadable_file bool | None

Whether to return only scenes which files are downloadable.

None
sort_by list[dict[str, str]] | dict[str, str] | str | None

Dataset properties to sort by.

None

Returns:

Type Description
SceneSearch

A SceneSearch instance that represents deferred query.

Source code in src/tellus_traveler/api/_scenes.py
def search(
    datasets: list[str] | None = None,
    bbox: list[float] | tuple[float, ...] | None = None,
    intersects: dict[str, Any] | None = None,
    start_datetime: str | datetime | None = None,
    end_datetime: str | datetime | None = None,
    query: dict[str, Any] | None = None,
    is_order_required: bool | None = None,
    only_downloadable_file: bool | None = None,
    sort_by: list[dict[str, str]] | dict[str, str] | str | None = None,
) -> SceneSearch:
    """Search scenes.

    <https://www.tellusxdp.com/docs/travelers/#/シーン/post_data_search_>

    Args:
        datasets: Dataset IDs.
        bbox: Bounding box of coordinates.
        intersects: GeoJSON Polygon geometry.
        start_datetime: Observation start datetime.
        end_datetime: Observation end datetime.
        query: Other queries for dataset properties. See the API doc for more details.
        is_order_required: Whether orders are required to download files.
        only_downloadable_file: Whether to return only scenes which files are
            downloadable.
        sort_by: Dataset properties to sort by.

    Returns:
        A [SceneSearch][tellus_traveler.models.SceneSearch] instance that
            represents deferred query.
    """
    if bbox is not None:
        if intersects is not None:
            raise ValueError("intersects and bbox cannot be set at the same time.")

        x1, y1, x2, y2 = bbox
        intersects = {
            "type": "Polygon",
            "coordinates": [
                [
                    [x1, y1],
                    [x2, y1],
                    [x2, y2],
                    [x1, y2],
                    [x1, y1],
                ]
            ],
        }

    if query is None:
        query = {}

    if start_datetime is not None:
        if "start_datetime" in query:
            raise ValueError("start_datetime is already set in query.")

        if isinstance(start_datetime, datetime):
            start_datetime = start_datetime.isoformat()

        query["start_datetime"] = {"gte": start_datetime}

    if end_datetime is not None:
        if "end_datetime" in query:
            raise ValueError("end_datetime is already set in query.")

        if isinstance(end_datetime, datetime):
            end_datetime = end_datetime.isoformat()

        query["end_datetime"] = {"lte": end_datetime}

    if isinstance(sort_by, str):
        sort_by = [{"field": sort_by}]
    elif isinstance(sort_by, dict):
        sort_by = [sort_by]

    params = {
        "datasets": datasets,
        "intersects": intersects,
        "query": query,
        "is_order_required": is_order_required,
        "only_downloadable_file": only_downloadable_file,
        "sort_by": sort_by,
    }

    # `null` is not allowed at `is_order_required` and `only_downloadable_file`.
    params = {k: v for k, v in params.items() if v is not None}

    return SceneSearch(params)

tellus_traveler.models

Model classes.

File

Bases: UserDict[str, Any]

File model.

Attributes:

Name Type Description
dataset_id str

Dataset ID that the file belongs to.

scene_id str

Scene ID that the file belongs to.

is_thumbnail bool

Whether the file is a thumbnail.

Source code in src/tellus_traveler/models/_file.py
class File(UserDict[str, Any]):
    """File model.

    Attributes:
        dataset_id: Dataset ID that the file belongs to.
        scene_id: Scene ID that the file belongs to.
        is_thumbnail: Whether the file is a thumbnail.
    """

    def __init__(
        self,
        dataset_id: str,
        scene_id: str,
        data: dict[str, Any],
        is_thumbnail: bool = False,
    ):
        self.dataset_id: str = dataset_id
        self.scene_id: str = scene_id
        self.is_thumbnail: bool = is_thumbnail
        super().__init__(data)

    def url(self) -> str:
        """Get a download URL of the file.

        Returns:
            A download URL of the file.
        """
        if self.is_thumbnail:
            return api.scene_thumbnail_url(
                self.dataset_id, self.scene_id, self.data["id"]
            )
        else:
            return api.scene_file_url(self.dataset_id, self.scene_id, self.data["id"])

    def download(self, dir: Path | str = ".", name: str | None = None) -> Path:
        """Download the file.

        Args:
            dir: Directory path to save the file.
            name: File name to save the file. If not given, the original file name is
                used.

        Returns:
            A `Path` instance of the downloaded file.
        """
        if name is None:
            name = str(self.data["name"])

        response = requests.get(self.url(), stream=True)
        response.raise_for_status()

        file_path = Path(dir, name)
        with file_path.open("wb") as f:
            for chunk in response.iter_content(chunk_size=1024):
                f.write(chunk)

        return file_path

download(dir='.', name=None)

Download the file.

Parameters:

Name Type Description Default
dir Path | str

Directory path to save the file.

'.'
name str | None

File name to save the file. If not given, the original file name is used.

None

Returns:

Type Description
Path

A Path instance of the downloaded file.

Source code in src/tellus_traveler/models/_file.py
def download(self, dir: Path | str = ".", name: str | None = None) -> Path:
    """Download the file.

    Args:
        dir: Directory path to save the file.
        name: File name to save the file. If not given, the original file name is
            used.

    Returns:
        A `Path` instance of the downloaded file.
    """
    if name is None:
        name = str(self.data["name"])

    response = requests.get(self.url(), stream=True)
    response.raise_for_status()

    file_path = Path(dir, name)
    with file_path.open("wb") as f:
        for chunk in response.iter_content(chunk_size=1024):
            f.write(chunk)

    return file_path

url()

Get a download URL of the file.

Returns:

Type Description
str

A download URL of the file.

Source code in src/tellus_traveler/models/_file.py
def url(self) -> str:
    """Get a download URL of the file.

    Returns:
        A download URL of the file.
    """
    if self.is_thumbnail:
        return api.scene_thumbnail_url(
            self.dataset_id, self.scene_id, self.data["id"]
        )
    else:
        return api.scene_file_url(self.dataset_id, self.scene_id, self.data["id"])

Scene

Scene model that wraps a GeoJSON Feature.

Attributes:

Name Type Description
__geo_interface__ dict[str, Any]

GeoJSON Feature dictionary. See https://gist.github.com/sgillies/2217756.

Source code in src/tellus_traveler/models/_scene.py
class Scene:
    """Scene model that wraps a GeoJSON Feature.

    Attributes:
        __geo_interface__: GeoJSON Feature dictionary.
            See https://gist.github.com/sgillies/2217756.
    """

    def __init__(self, geojson: dict[str, Any]):  # noqa: D107
        self.__geo_interface__: dict[str, Any] = geojson

    def __repr__(self):  # noqa: D105
        return f"<tellus_traveler.Scene id={self.id}>"

    def __getitem__(self, key: str) -> Any:
        """Gets a property value by key."""
        if key in self.properties:
            return self.properties[key]
        else:
            raise KeyError(key)

    def get(self, key: str, default: Any = None) -> Any:
        """Gets a property value by key. Returns `default` if the key is not found."""
        try:
            return self[key]
        except KeyError:
            return default

    @property
    def id(self) -> str:
        """Scene ID."""
        return self.__geo_interface__["id"]

    @property
    def dataset_id(self) -> str:
        """Dataset ID that the scene belongs to."""
        return self.__geo_interface__["dataset_id"]

    @property
    def geometry(self) -> dict[str, Any]:
        """GeoJSON Geometry dictionary."""
        return self.__geo_interface__["geometry"]

    @property
    def properties(self) -> dict[str, Any]:
        """Dataset properties."""
        return self.__geo_interface__["properties"]

    def files(self) -> list[File]:
        """Get files belonging to the scene.

        Returns:
            A list of `File` instances.
        """
        return api.scene_files(self.dataset_id, self.id)

    def download_all_files(self, dir: Path | str | None = None) -> Path:
        """Download all files concurrently.

        Args:
            dir: Directory path to save the files. If not given, creates a directory
                with `tellus:name` in the current directory and saves the files there.

        Returns:
            A `Path` instance of the directory where the files are saved.
        """
        files = self.files()

        if len(files) > len(set(file["name"] for file in files)):
            raise ValueError("File names are not unique.")

        if dir is None:
            dir = Path(self["tellus:name"])
            dir.mkdir(exist_ok=True)

        threads = [Thread(target=file.download, args=(dir,)) for file in files]

        for thread in threads:
            thread.start()

        for thread in threads:
            thread.join()

        return Path(dir)

    def thumbnails(self) -> list[File]:
        """Get thumbnails belonging to the scene.

        Returns:
            A list of `File` instances.
        """
        return api.scene_thumbnails(self.dataset_id, self.id)

dataset_id: str property

Dataset ID that the scene belongs to.

geometry: dict[str, Any] property

GeoJSON Geometry dictionary.

id: str property

Scene ID.

properties: dict[str, Any] property

Dataset properties.

__getitem__(key)

Gets a property value by key.

Source code in src/tellus_traveler/models/_scene.py
def __getitem__(self, key: str) -> Any:
    """Gets a property value by key."""
    if key in self.properties:
        return self.properties[key]
    else:
        raise KeyError(key)

download_all_files(dir=None)

Download all files concurrently.

Parameters:

Name Type Description Default
dir Path | str | None

Directory path to save the files. If not given, creates a directory with tellus:name in the current directory and saves the files there.

None

Returns:

Type Description
Path

A Path instance of the directory where the files are saved.

Source code in src/tellus_traveler/models/_scene.py
def download_all_files(self, dir: Path | str | None = None) -> Path:
    """Download all files concurrently.

    Args:
        dir: Directory path to save the files. If not given, creates a directory
            with `tellus:name` in the current directory and saves the files there.

    Returns:
        A `Path` instance of the directory where the files are saved.
    """
    files = self.files()

    if len(files) > len(set(file["name"] for file in files)):
        raise ValueError("File names are not unique.")

    if dir is None:
        dir = Path(self["tellus:name"])
        dir.mkdir(exist_ok=True)

    threads = [Thread(target=file.download, args=(dir,)) for file in files]

    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    return Path(dir)

files()

Get files belonging to the scene.

Returns:

Type Description
list[File]

A list of File instances.

Source code in src/tellus_traveler/models/_scene.py
def files(self) -> list[File]:
    """Get files belonging to the scene.

    Returns:
        A list of `File` instances.
    """
    return api.scene_files(self.dataset_id, self.id)

get(key, default=None)

Gets a property value by key. Returns default if the key is not found.

Source code in src/tellus_traveler/models/_scene.py
def get(self, key: str, default: Any = None) -> Any:
    """Gets a property value by key. Returns `default` if the key is not found."""
    try:
        return self[key]
    except KeyError:
        return default

thumbnails()

Get thumbnails belonging to the scene.

Returns:

Type Description
list[File]

A list of File instances.

Source code in src/tellus_traveler/models/_scene.py
def thumbnails(self) -> list[File]:
    """Get thumbnails belonging to the scene.

    Returns:
        A list of `File` instances.
    """
    return api.scene_thumbnails(self.dataset_id, self.id)

SceneSearch

Search query for scenes.

Attributes:

Name Type Description
params dict[str, Any]

Search query parameters.

Source code in src/tellus_traveler/models/_scene_search.py
class SceneSearch:
    """Search query for scenes.

    Attributes:
        params: Search query parameters.
    """

    def __init__(self, params: dict[str, Any]):  # noqa: D107
        self.params: dict[str, Any] = params

    def __repr__(self):  # noqa: D105
        return f"<tellus_traveler.SceneSearch params={self.params}>"

    def total(self) -> int:
        """Gets the total number of scenes that match the query.

        Returns:
            The total number of scenes.
        """
        response = self._request(self.params)
        return response["meta"]["total"]

    def scenes(self) -> Iterator[Scene]:
        """Returns [`Iterator`][collections.abc.Iterator] of scenes matched the query.

        Yields:
            Scene objects that match the query.
        """
        for page in self.pages():
            for scene_dict in page["features"]:
                yield Scene(scene_dict)

    def pages(self) -> Iterator[dict[str, Any]]:
        """Returns [`Iterator`][collections.abc.Iterator] of the search result pages.

        Yields:
            Search result dict that represents GeoJSON FeatureCollection.
        """
        count = 0
        params = self.params

        while True:
            page = self._request(params)

            meta = page.pop("meta")
            yield page

            count += len(page["features"])
            if count >= meta["total"]:
                break

            params = meta["search-condition"]

    @staticmethod
    def _request(params: dict[str, Any]) -> dict[str, Any]:
        return http_client.post("/data-search/", **params)

pages()

Returns Iterator of the search result pages.

Yields:

Type Description
dict[str, Any]

Search result dict that represents GeoJSON FeatureCollection.

Source code in src/tellus_traveler/models/_scene_search.py
def pages(self) -> Iterator[dict[str, Any]]:
    """Returns [`Iterator`][collections.abc.Iterator] of the search result pages.

    Yields:
        Search result dict that represents GeoJSON FeatureCollection.
    """
    count = 0
    params = self.params

    while True:
        page = self._request(params)

        meta = page.pop("meta")
        yield page

        count += len(page["features"])
        if count >= meta["total"]:
            break

        params = meta["search-condition"]

scenes()

Returns Iterator of scenes matched the query.

Yields:

Type Description
Scene

Scene objects that match the query.

Source code in src/tellus_traveler/models/_scene_search.py
def scenes(self) -> Iterator[Scene]:
    """Returns [`Iterator`][collections.abc.Iterator] of scenes matched the query.

    Yields:
        Scene objects that match the query.
    """
    for page in self.pages():
        for scene_dict in page["features"]:
            yield Scene(scene_dict)

total()

Gets the total number of scenes that match the query.

Returns:

Type Description
int

The total number of scenes.

Source code in src/tellus_traveler/models/_scene_search.py
def total(self) -> int:
    """Gets the total number of scenes that match the query.

    Returns:
        The total number of scenes.
    """
    response = self._request(self.params)
    return response["meta"]["total"]

tellus_traveler.http_client

Thin HTTP client for Tellus Traveler API.

HTTPError

Bases: IOError

An HTTP error occurred.

Attributes:

Name Type Description
response Response

The response object.

Source code in src/tellus_traveler/http_client.py
class HTTPError(IOError):
    """An HTTP error occurred.

    Attributes:
        response: The response object.
    """

    def __init__(self, message: str, response: requests.Response):  # noqa: D107
        self.response: requests.Response = response
        super().__init__(message)

get(path, **params)

Creates a GET request to Tellus Traveler API.

Parameters:

Name Type Description Default
path str

Path to the API endpoint.

required
params Any

Query parameters.

{}

Returns:

Type Description
Any

The JSON response body as a Python object.

Source code in src/tellus_traveler/http_client.py
def get(path: str, **params: Any) -> Any:
    """Creates a GET request to Tellus Traveler API.

    Args:
        path: Path to the API endpoint.
        params: Query parameters.

    Returns:
        The JSON response body as a Python object.
    """
    return _request("get", path, params=params)

post(path, **json)

Creates a POST request to Tellus Traveler API.

Parameters:

Name Type Description Default
path str

Path to the API endpoint.

required
json Any

JSON data to send in the request body.

{}

Returns:

Type Description
Any

The JSON response body as a Python object.

Source code in src/tellus_traveler/http_client.py
def post(path: str, **json: Any) -> Any:
    """Creates a POST request to Tellus Traveler API.

    Args:
        path: Path to the API endpoint.
        json: JSON data to send in the request body.

    Returns:
        The JSON response body as a Python object.
    """
    return _request("post", path, json=json)