diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 000000000..e69de29bb diff --git a/404.html b/404.html new file mode 100644 index 000000000..5523e98d7 --- /dev/null +++ b/404.html @@ -0,0 +1,2554 @@ + + + +
+ + + + + + + + + + + + + + + + +Important
+This has been deprecated. You can now pass environment_dependency=lambda: {"GDAL_DISABLE_READDIR_ON_OPEN":"FALSE"}
to the Tiler Factory. This will be passed to a rasterio.Env()
context manager on top of all gdal related blocks.
from titiler.core.factory import TilerFactory
+cog = TilerFactory(
+ reader=COGReader,
+ router_prefix="cog",
+ environment_dependency=lambda: {"GDAL_DISABLE_READDIR_ON_OPEN":"FALSE"},
+)
+
Sometimes, specifically when using GDAL, it can be useful to have environment variables set for certain endpoints
+(e.g. when using Landsat data on AWS you need GDAL_DISABLE_READDIR_ON_OPEN=FALSE
but you don't want this environment variable set for other endpoints). To be able to do this
+we created a custom APIRoute class which wraps classic fastapi APIRoute with a rasterio.Env()
block: github.com/developmentseed/titiler/blob/8a7127ca56631c2c327713d99e80285048c3aa6c/titiler/custom/routing.py#L13-L41
Example: +
from fastapi import FastAPI, APIRouter
+from rasterio._env import get_gdal_config
+from titiler.core.routing import apiroute_factory
+from titiler.core.factory import TilerFactory
+
+app = FastAPI()
+route_class = apiroute_factory({"GDAL_DISABLE_READDIR_ON_OPEN": "FALSE"})
+router = APIRouter(route_class=route_class)
+
+tiler = TilerFactory(router=router)
+
+@router.get("/simple")
+def simple():
+ """should return FALSE."""
+ res = get_gdal_config("GDAL_DISABLE_READDIR_ON_OPEN")
+ return {"env": res}
+
+app.include_router(router)
+
Important
+This has only be tested for python 3.6 and 3.7.
+Starting with titiler>=0.8
, we added the possibility to apply custom algorithms on Image outputs from tile
, crop
or preview
endpoints.
The algorithms are meant to overcome the limitation of expression
(using numexpr) by allowing more complex operations.
We added a set of custom algorithms:
+hillshade
: Create hillshade from elevation datasetcontours
: Create contours lines (raster) from elevation datasetterrarium
: Mapzen's format to encode elevation value in RGB values (github.com/tilezen/joerd/blob/master/docs/formats.md#terrarium)terrainrgb
: Mapbox's format to encode elevation value in RGB values (docs.mapbox.com/data/tilesets/guides/access-elevation-data/)normalizedIndex
: Normalized Difference Index (e.g NDVI)# return a
+httpx.get(
+ "http://127.0.0.1:8081/cog/tiles/16/34059/23335",
+ params={
+ "url": "https://data.geo.admin.ch/ch.swisstopo.swissalti3d/swissalti3d_2019_2573-1085/swissalti3d_2019_2573-1085_0.5_2056_5728.tif",
+ "buffer": 3, # By default hillshade will crop the output with a 3pixel buffer, so we need to apply a buffer on the tile
+ "algorithm": "hillshade",
+ },
+)
+
# Pass algorithm parameter as a json string
+httpx.get(
+ "http://127.0.0.1:8081/cog/preview",
+ params={
+ "url": "https://data.geo.admin.ch/ch.swisstopo.swissalti3d/swissalti3d_2019_2573-1085/swissalti3d_2019_2573-1085_0.5_2056_5728.tif",
+ "algorithm": "contour",
+ "algorithm_params": json.dumps({"minz": 1600, "maxz": 2100}) # algorithm params HAVE TO be provided as a JSON string
+ },
+)
+
A titiler'w Algorithm
must be defined using titiler.core.algorithm.BaseAlgorithm
base class.
class BaseAlgorithm(BaseModel, metaclass=abc.ABCMeta):
+ """Algorithm baseclass.
+
+ Note: attribute starting with `input_` or `output_` are considered as metadata
+
+ """
+
+ # metadata
+ input_nbands: int
+ output_nbands: int
+ output_dtype: str
+ output_min: Optional[Sequence]
+ output_max: Optional[Sequence]
+
+ @abc.abstractmethod
+ def __call__(self, img: ImageData) -> ImageData:
+ """Apply algorithm"""
+ ...
+
+ class Config:
+ """Config for model."""
+
+ extra = "allow"
+
This base class defines that algorithm:
+HAVE TO implement an __call__
method which takes an ImageData as input and return an ImageData. Using __call__
let us use the object as a callable (e.g Algorithm(**kwargs)(image)
).
can have input/output metadata (informative)
+can haveparameters
(enabled by extra = "allow"
pydantic config)
Here is a simple example of a custom Algorithm:
+from titiler.core.algorithm import BaseAlgorithm
+from rio_tiler.models import ImageData
+
+class Multiply(BaseAlgorithm):
+
+ # Parameters
+ factor: int # There is no default, which means calls to this algorithm without any parameter will fail
+
+ # We don't set any metadata for this Algorithm
+
+ def __call__(self, img: ImageData) -> ImageData:
+ # Multiply image data bcy factor
+ data = img.data * self.factor
+
+ # Create output ImageData
+ return ImageData(
+ data,
+ img.mask,
+ assets=img.assets,
+ crs=img.crs,
+ bounds=img.bounds,
+ )
+
Using a Pydantic's BaseModel
class to construct the custom algorithm enables two things parametrization and type casting/validation.
If we look at the Multiply
algorithm, we can see it needs a factor
parameter. In Titiler (in the post_process dependency) we will pass this parameter via query string (e.g /preview.png?algo=multiply&algo_parameter={"factor":3}
) and pydantic will make sure we use the right types/values.
# Available algorithm
+algo = {"multiply": Multiply}
+
+def post_process_dependency(
+ algorithm: Literal[tuple(algo.keys())] = Query(None, description="Algorithm name"),
+ algorithm_params: str = Query(None, description="Algorithm parameter"),
+) -> Optional[BaseAlgorithm]:
+ """Data Post-Processing dependency."""
+ # Parse `algorithm_params` JSON parameters
+ kwargs = json.loads(algorithm_params) if algorithm_params else {}
+ if algorithm:
+ # Here we construct the Algorithm Object with the kwargs from the `algo_params` query-parameter
+ return algo[algorithm](**kwargs)
+
+ return None
+
To be able to use your own algorithm in titiler's endpoint you need to create a Dependency
to tell the application what algorithm are available.
To ease the dependency creation, we added a dependency
property in the titiler.core.algorithm.Algorithms
class, which will return a FastAPI dependency to be added to the endpoints.
Note: The Algorithms
class is a store for the algorithm that can be extented using the .register()
method.
from typing import Callable
+from titiler.core.algorithm import algorithms as default_algorithms
+from titiler.core.algorithm import Algorithms
+from titiler.core.factory import TilerFactory
+
+# Add the `Multiply` algorithm to the default ones
+algorithms: Algorithms = default_algorithms.register({"multiply": Multiply})
+
+# Create a PostProcessParams dependency
+PostProcessParams: Callable = algorithms.dependency
+
+endpoints = TilerFactory(process_dependency=PostProcessParams)
+
When creating a map tile (or other images), we will fist apply the algorithm
then the rescaling
and finally the color_formula
.
with reader(url as src_dst:
+ image = src_dst.tile(
+ x,
+ y,
+ z,
+ )
+ dst_colormap = getattr(src_dst, "colormap", None)
+
+# Apply algorithm
+if post_process:
+ image = post_process(image)
+
+# Apply data rescaling
+if rescale:
+ image.rescale(rescale)
+
+# Apply color-formula
+if color_formula:
+ image.apply_color_formula(color_formula)
+
+# Determine the format
+if not format:
+ format = ImageType.jpeg if image.mask.all() else ImageType.png
+
+# Image Rendering
+return image.render(
+ img_format=format.driver,
+ colormap=colormap or dst_colormap,
+ **format.profile,
+)
+
Starting with titiler>=0.11
, we added a new titiler package titiler.extensions
which aim to ease the addition of optional
endpoints to factories.
In titiler.core.factory.BaseTilerFactory
class, we've added a new attribute: extensions: List[FactoryExtension] = field(default_factory=list)
. The list
of extension will then be used in the post-init
step such as:
def __post_init__(self):
+ """Post Init: register route and configure specific options."""
+ # Register endpoints
+ self.register_routes()
+
+ # Register Extensions
+ for ext in self.extensions:
+ ext.register(self)
+
+ # Update endpoints dependencies
+ for scopes, dependencies in self.route_dependencies:
+ self.add_route_dependencies(scopes=scopes, dependencies=dependencies)
+
We defined extension using an Abstract Base Class to make sure they implement a register
method:
@dataclass
+class FactoryExtension(metaclass=abc.ABCMeta):
+ """Factory Extension."""
+
+ @abc.abstractmethod
+ def register(self, factory: "BaseTilerFactory"):
+ """Register extension to the factory."""
+ ...
+
/validate
endpoint which return the content of rio-cogeo info
methodtitiler.extensions["cogeo"]
(installs rio-cogeo
)/viewer
endpoint which return an HTML viewer for simple COGs/viewer
endpoint which return an HTML viewer for STAC item/stac
endpoint which return an HTML viewer for STAC itemtitiler.extensions["stac"]
(installs rio-stac
)/wms
endpoint to support OGC WMS specification (GetCapabilities
and GetMap
)Extensions must be set at TilerFactory's creation using the extensions=
options.
from fastapi import FastAPI
+from titiler.core.factory import TilerFactory
+from titiler.extensions import cogValidateExtension
+
+# Create a FastAPI application
+app = FastAPI(description="A lightweight Cloud Optimized GeoTIFF tile server")
+
+# Create a set of endpoints using TiTiler TilerFactory
+tiler = TilerFactory(
+ router_prefix="/cog",
+ extensions=[
+ cogValidateExtension() # the cogeoExtension will add a rio-cogeo /validate endpoint
+ ]
+)
+
+# Register endpoints to the application
+app.include_router(tiler.router, prefix="/cog")
+
See titiler.application for a full example.
+from dataclasses import dataclass, field
+from typing import Tuple, List, Optional
+
+import rasterio
+from starlette.responses import Response
+from fastapi import Depends, FastAPI, Query
+from titiler.core.factory import BaseTilerFactory, FactoryExtension, TilerFactory
+from titiler.core.dependencies import RescalingParams
+from titiler.core.factory import TilerFactory
+from titiler.core.resources.enums import ImageType
+
+
+@dataclass
+class thumbnailExtension(FactoryExtension):
+ """Add endpoint to a TilerFactory."""
+
+ # Set some options
+ max_size: int = field(default=128)
+
+ # Register method is mandatory and must take a BaseTilerFactory object as input
+ def register(self, factory: BaseTilerFactory):
+ """Register endpoint to the tiler factory."""
+
+ # register an endpoint to the factory's router
+ @factory.router.get(
+ "/thumbnail",
+ responses={
+ 200: {
+ "content": {
+ "image/png": {},
+ "image/jpeg": {},
+ },
+ "description": "Return an image.",
+ }
+ },
+ response_class=Response,
+ )
+ def thumbnail(
+ # we can reuse the factory dependency
+ src_path: str = Depends(factory.path_dependency),
+ layer_params=Depends(factory.layer_dependency),
+ dataset_params=Depends(factory.dataset_dependency),
+ post_process=Depends(factory.process_dependency),
+ rescale: Optional[List[Tuple[float, ...]]] = Depends(RescalingParams),
+ color_formula: Optional[str] = Query(
+ None,
+ title="Color Formula",
+ description="rio-color formula (info: https://github.com/mapbox/rio-color)",
+ ),
+ colormap=Depends(factory.colormap_dependency),
+ render_params=Depends(factory.render_dependency),
+ reader_params=Depends(factory.reader_dependency),
+ env=Depends(factory.environment_dependency),
+ ):
+ with rasterio.Env(**env):
+ with factory.reader(src_path, **reader_params.as_dict()) as src:
+ image = src.preview(
+ max_size=self.max_size,
+ **layer_params.as_dict(),
+ **dataset_params.as_dict(),
+ )
+
+ if post_process:
+ image = post_process(image)
+
+ if rescale:
+ image.rescale(rescale)
+
+ if color_formula:
+ image.apply_color_formula(color_formula)
+
+ format = ImageType.jpeg if image.mask.all() else ImageType.png
+
+ content = image.render(
+ img_format=format.driver,
+ colormap=colormap,
+ **format.profile,
+ **render_params.as_dict(),
+ )
+
+ return Response(content, media_type=format.mediatype)
+
+# Use it
+app = FastAPI()
+tiler = TilerFactory(
+ extensions=[
+ thumbnailExtension(max_size=64)
+ ]
+)
+app.include_router(tiler.router)
+
TiTiler
is designed to help user customize input/output for each endpoint. This section goes over some simple customization examples.
Add user defined colormap to the default colormaps provided by rio-tiler
+from fastapi import FastAPI
+
+from rio_tiler.colormap import cmap as default_cmap
+
+from titiler.core.dependencies import create_colormap_dependency
+from titiler.core.factory import TilerFactory
+
+
+app = FastAPI(title="My simple app with custom TMS")
+
+cmap_values = {
+ "cmap1": {6: (4, 5, 6, 255)},
+}
+# add custom colormap `cmap1` to the default colormaps
+cmap = default_cmap.register(cmap_values)
+ColorMapParams = create_colormap_dependency(cmap)
+
+
+cog = TilerFactory(colormap_dependency=ColorMapParams)
+app.include_router(cog.router)
+
reader_dependency
¶One common customization could be to create your own path_dependency
. This dependency is used on all endpoint and pass inputs to the Readers (MosaicBackend, COGReader, STACReader...).
Here an example which allow a mosaic to be passed by a mosaic name
instead of a full S3 url.
import os
+import re
+
+from fastapi import FastAPI, HTTPException, Query
+
+from titiler.mosaic.factory import MosaicTilerFactory
+
+
+MOSAIC_BACKEND = os.getenv("TITILER_MOSAIC_BACKEND")
+MOSAIC_HOST = os.getenv("TITILER_MOSAIC_HOST")
+
+
+def MosaicPathParams(
+ mosaic: str = Query(..., description="mosaic name")
+) -> str:
+ """Create dataset path from args"""
+ # mosaic name should be in form of `{user}.{layername}`
+ if not re.match(self.mosaic, r"^[a-zA-Z0-9-_]{1,32}\.[a-zA-Z0-9-_]{1,32}$"):
+ raise HTTPException(
+ status_code=400,
+ detail=f"Invalid mosaic name {self.input}.",
+ )
+
+ return f"{MOSAIC_BACKEND}{MOSAIC_HOST}/{self.input}.json.gz"
+
+
+app = FastAPI()
+mosaic = MosaicTilerFactory(path_dependency=MosaicPathParams)
+app.include_router(mosaic.router)
+
The endpoint url will now look like: {endpoint}/mosaic/tilejson.json?mosaic=vincent.mosaic
from morecantile import tms, TileMatrixSet
+from pyproj import CRS
+
+from titiler.core.factory import TilerFactory
+
+# 1. Create Custom TMS
+EPSG6933 = TileMatrixSet.custom(
+ (-17357881.81713629, -7324184.56362408, 17357881.81713629, 7324184.56362408),
+ CRS.from_epsg(6933),
+ identifier="EPSG6933",
+ matrix_scale=[1, 1],
+)
+
+# 2. Register TMS
+tms = tms.register([EPSG6933])
+
+# 3. Create Tiler
+COGTilerWithCustomTMS = TilerFactory(supported_tms=tms)
+
from dataclasses import dataclass
+from typing import List, Optional
+
+from titiler.mosaic.factory import MosaicTilerFactory
+from titiler.core.errors import BadRequestError
+from cogeo_mosaic.mosaic import MosaicJSON
+from cogeo_mosaic.utils import get_footprints
+import rasterio
+
+from pydantic import BaseModel
+
+
+# Models from POST/PUT Body
+class CreateMosaicJSON(BaseModel):
+ """Request body for MosaicJSON creation"""
+
+ files: List[str] # Files to add to the mosaic
+ url: str # path where to save the mosaicJSON
+ minzoom: Optional[int] = None
+ maxzoom: Optional[int] = None
+ max_threads: int = 20
+ overwrite: bool = False
+
+
+class UpdateMosaicJSON(BaseModel):
+ """Request body for updating an existing MosaicJSON"""
+
+ files: List[str] # Files to add to the mosaic
+ url: str # path where to save the mosaicJSON
+ max_threads: int = 20
+ add_first: bool = True
+
+
+@dataclass
+class CustomMosaicFactory(MosaicTilerFactory):
+
+ def register_routes(self):
+ """Update the class method to add create/update"""
+ super().register_routes()
+ # new methods/endpoint
+ self.create()
+ self.update()
+
+ def create(self):
+ """Register / (POST) Create endpoint."""
+
+ @self.router.post(
+ "", response_model=MosaicJSON, response_model_exclude_none=True
+ )
+ def create(
+ body: CreateMosaicJSON,
+ env=Depends(self.environment_dependency),
+ ):
+ """Create a MosaicJSON"""
+ # Write can write to either a local path, a S3 path...
+ # See https://developmentseed.org/cogeo-mosaic/advanced/backends/ for the list of supported backends
+
+ # Create a MosaicJSON file from a list of URL
+ mosaic = MosaicJSON.from_urls(
+ body.files,
+ minzoom=body.minzoom,
+ maxzoom=body.maxzoom,
+ max_threads=body.max_threads,
+ )
+
+ # Write the MosaicJSON using a cogeo-mosaic backend
+ with rasterio.Env(**env):
+ with self.reader(
+ body.url, mosaic_def=mosaic, reader=self.dataset_reader
+ ) as mosaic:
+ try:
+ mosaic.write(overwrite=body.overwrite)
+ except NotImplementedError:
+ raise BadRequestError(
+ f"{mosaic.__class__.__name__} does not support write operations"
+ )
+ return mosaic.mosaic_def
+
+ def update(self):
+ """Register / (PUST) Update endpoint."""
+
+ @self.router.put(
+ "", response_model=MosaicJSON, response_model_exclude_none=True
+ )
+ def update_mosaicjson(
+ body: UpdateMosaicJSON,
+ env=Depends(self.environment_dependency),
+ ):
+ """Update an existing MosaicJSON"""
+ with rasterio.Env(**env):
+ with self.reader(body.url, reader=self.dataset_reader) as mosaic:
+ features = get_footprints(body.files, max_threads=body.max_threads)
+ try:
+ mosaic.update(features, add_first=body.add_first, quiet=True)
+ except NotImplementedError:
+ raise BadRequestError(
+ f"{mosaic.__class__.__name__} does not support update operations"
+ )
+ return mosaic.mosaic_def
+
If you are new to the concept of Dependency Injection, please read this awesome tutorial: fastapi.tiangolo.com/tutorial/dependencies/
+In titiler Factories
, we use the dependencies to define the inputs for each endpoint (and thus the OpenAPI documentation).
Example: +
from dataclasses import dataclass
+from fastapi import Depends, FastAPI, Query
+from titiler.core.dependencies import DefaultDependency
+from typing_extensions import Annotated
+from rio_tiler.io import Reader
+
+@dataclass
+class ImageParams(DefaultDependency):
+ max_size: Annotated[
+ int, Query(description="Maximum image size to read onto.")
+ ] = 1024
+
+app = FastAPI()
+
+# Simple preview endpoint
+@app.get("/preview.png")
+def preview(
+ url: str = Query(..., description="data set URL"),
+ params: ImageParams = Depends(),
+):
+ with Reader(url) as cog:
+ img = cog.preview(**params.as_dict()) # we use `DefaultDependency().as_dict()` to pass only non-None parameters
+ # or
+ img = cog.preview(max_size=params.max_size)
+ ...
+
Important
+In the example above, we create a custom ImageParams
dependency which will then be injected to the preview
endpoint to add max_size, height and width query string parameters.
Using titiler.core.dependencies.DefaultDependency
, we can use .as_dict(exclude_none=True/False)
method to unpack
the object parameters. This can be useful if method or reader do not take the same parameters.
Define assets
.
Name | +Type | +Required | +Default | +
---|---|---|---|
assets | +Query (str) | +No | +None | +
@dataclass
+class AssetsParams(DefaultDependency):
+ """Assets parameters."""
+
+ assets: List[str] = Query(
+ None,
+ title="Asset names",
+ description="Asset's names.",
+ openapi_examples={
+ "one-asset": {
+ "description": "Return results for asset `data`.",
+ "value": ["data"],
+ },
+ "multi-assets": {
+ "description": "Return results for assets `data` and `cog`.",
+ "value": ["data", "cog"],
+ },
+ },
+ )
+
Define assets
with option of per-asset
expression with asset_expression
option.
Name | +Type | +Required | +Default | +
---|---|---|---|
assets | +Query (str) | +No | +None | +
asset_indexes | +Query (str) | +No | +None | +
asset_expression | +Query (str) | +No | +False | +
@dataclass
+class AssetsBidxParams(AssetsParams):
+ """Assets, Asset's band Indexes and Asset's band Expression parameters."""
+
+ asset_indexes: Annotated[
+ Optional[Sequence[str]],
+ Query(
+ title="Per asset band indexes",
+ description="Per asset band indexes",
+ alias="asset_bidx",
+ openapi_examples={
+ "one-asset": {
+ "description": "Return indexes 1,2,3 of asset `data`.",
+ "value": ["data|1;2;3"],
+ },
+ "multi-assets": {
+ "description": "Return indexes 1,2,3 of asset `data` and indexes 1 of asset `cog`",
+ "value": ["data|1;2;3", "cog|1"],
+ },
+ },
+ ),
+ ] = None
+
+ asset_expression: Annotated[
+ Optional[Sequence[str]],
+ Query(
+ title="Per asset band expression",
+ description="Per asset band expression",
+ openapi_examples={
+ "one-asset": {
+ "description": "Return results for expression `b1*b2+b3` of asset `data`.",
+ "value": ["data|b1*b2+b3"],
+ },
+ "multi-assets": {
+ "description": "Return results for expressions `b1*b2+b3` for asset `data` and `b1+b3` for asset `cog`.",
+ "value": ["data|b1*b2+b3", "cog|b1+b3"],
+ },
+ },
+ ),
+ ] = None
+
+ def __post_init__(self):
+ """Post Init."""
+ if self.asset_indexes:
+ self.asset_indexes: Dict[str, Sequence[int]] = { # type: ignore
+ idx.split("|")[0]: list(map(int, idx.split("|")[1].split(",")))
+ for idx in self.asset_indexes
+ }
+
+ if self.asset_expression:
+ self.asset_expression: Dict[str, str] = { # type: ignore
+ idx.split("|")[0]: idx.split("|")[1] for idx in self.asset_expression
+ }
+
Define assets
.
Name | +Type | +Required | +Default | +
---|---|---|---|
assets | +Query (str) | +No* | +None | +
expression | +Query (str) | +No* | +None | +
asset_indexes | +Query (str) | +No | +None | +
asset_as_band | +Query (bool) | +No | +False | +
* assets
or expression
is required.
@dataclass
+class AssetsBidxExprParams(AssetsParams):
+ """Assets, Expression and Asset's band Indexes parameters."""
+
+ expression: Annotated[
+ Optional[str],
+ Query(
+ title="Band Math expression",
+ description="Band math expression between assets",
+ openapi_examples={
+ "simple": {
+ "description": "Return results of expression between assets.",
+ "value": "asset1_b1 + asset2_b1 / asset3_b1",
+ },
+ },
+ ),
+ ] = None
+
+ asset_indexes: Annotated[
+ Optional[Sequence[str]],
+ Query(
+ title="Per asset band indexes",
+ description="Per asset band indexes (coma separated indexes)",
+ alias="asset_bidx",
+ openapi_examples={
+ "one-asset": {
+ "description": "Return indexes 1,2,3 of asset `data`.",
+ "value": ["data|1,2,3"],
+ },
+ "multi-assets": {
+ "description": "Return indexes 1,2,3 of asset `data` and indexes 1 of asset `cog`",
+ "value": ["data|1,2,3", "cog|1"],
+ },
+ },
+ ),
+ ] = None
+
+ asset_as_band: Annotated[
+ Optional[bool],
+ Query(
+ title="Consider asset as a 1 band dataset",
+ description="Asset as Band",
+ ),
+ ] = None
+
+ def __post_init__(self):
+ """Post Init."""
+ if not self.assets and not self.expression:
+ raise MissingAssets(
+ "assets must be defined either via expression or assets options."
+ )
+
+ if self.asset_indexes:
+ self.asset_indexes: Dict[str, Sequence[int]] = { # type: ignore
+ idx.split("|")[0]: list(map(int, idx.split("|")[1].split(",")))
+ for idx in self.asset_indexes
+ }
+
Define assets
. Without requirement on assets nor expression.
Name | +Type | +Required | +Default | +
---|---|---|---|
assets | +Query (str) | +No | +None | +
expression | +Query (str) | +No | +None | +
asset_indexes | +Query (str) | +No | +None | +
asset_as_band | +Query (bool) | +No | +False | +
@dataclass
+class AssetsBidxExprParamsOptional(AssetsBidxExprParams):
+ """Assets, Expression and Asset's band Indexes parameters but with no requirement."""
+
+ def __post_init__(self):
+ """Post Init."""
+ if self.asset_indexes:
+ self.asset_indexes: Dict[str, Sequence[int]] = { # type: ignore
+ idx.split("|")[0]: list(map(int, idx.split("|")[1].split(",")))
+ for idx in self.asset_indexes
+ }
+
Define bands
.
Name | +Type | +Required | +Default | +
---|---|---|---|
bands | +Query (str) | +No | +None | +
@dataclass
+class BandsParams(DefaultDependency):
+ """Band names parameters."""
+
+ bands: List[str] = Query(
+ None,
+ title="Band names",
+ description="Band's names.",
+ openapi_examples={
+ "one-band": {
+ "description": "Return results for band `B01`.",
+ "value": ["B01"],
+ },
+ "multi-bands": {
+ "description": "Return results for bands `B01` and `B02`.",
+ "value": ["B01", "B02"],
+ },
+ },
+ )
+
Define bands
.
Name | +Type | +Required | +Default | +
---|---|---|---|
bands | +Query (str) | +No* | +None | +
expression | +Query (str) | +No* | +None | +
* bands
or expression
is required.
@dataclass
+class BandsExprParamsOptional(ExpressionParams, BandsParams):
+ """Optional Band names and Expression parameters."""
+
+ pass
+
Define bands
.
Name | +Type | +Required | +Default | +
---|---|---|---|
bands | +Query (str) | +No | +None | +
expression | +Query (str) | +No | +None | +
@dataclass
+class BandsExprParamsOptional(ExpressionParams, BandsParams):
+ """Optional Band names and Expression parameters."""
+
+ pass
+
BidxParams
¶Define band indexes.
+Name | +Type | +Required | +Default | +
---|---|---|---|
bidx | +Query (int) | +No | +None | +
@dataclass
+class BidxParams(DefaultDependency):
+ """Band Indexes parameters."""
+
+ indexes: Annotated[
+ Optional[List[int]],
+ Query(
+ title="Band indexes",
+ alias="bidx",
+ description="Dataset band indexes",
+ openapi_examples={"one-band": {"value": [1]}, "multi-bands": {"value": [1, 2, 3]}},
+ ),
+ ] = None
+
ExpressionParams
¶Define band expression.
+Name | +Type | +Required | +Default | +
---|---|---|---|
expression | +Query (str) | +No | +None | +
@dataclass
+class ExpressionParams(DefaultDependency):
+ """Expression parameters."""
+
+ expression: Annotated[
+ Optional[str],
+ Query(
+ title="Band Math expression",
+ description="rio-tiler's band math expression",
+ openapi_examples={
+ "simple": {"description": "Simple band math.", "value": "b1/b2"},
+ "multi-bands": {
+ "description": "Semicolon (;) delimited expressions (band1: b1/b2, band2: b2+b3).",
+ "value": "b1/b2;b2+b3",
+ },
+ },
+ ),
+ ] = None
+
BidxExprParams
¶Define band indexes or expression.
+Name | +Type | +Required | +Default | +
---|---|---|---|
bidx | +Query (int) | +No | +None | +
expression | +Query (str) | +No | +None | +
@dataclass
+class BidxExprParams(ExpressionParams, BidxParams):
+ """Band Indexes and Expression parameters."""
+
+ pass
+
ColorFormulaParams
¶Color Formula option (see vincentsarago/color-operations).
+Name | +Type | +Required | +Default | +
---|---|---|---|
color_formula | +Query (str) | +No | +None | +
def ColorFormulaParams(
+ color_formula: Annotated[
+ Optional[str],
+ Query(
+ title="Color Formula",
+ description="rio-color formula (info: https://github.com/mapbox/rio-color)",
+ ),
+ ] = None,
+) -> Optional[str]:
+ """ColorFormula Parameter."""
+ return color_formula
+
ColorMapParams
¶Colormap options. See titiler.core.dependencies.
+Name | +Type | +Required | +Default | +
---|---|---|---|
colormap_name | +Query (str) | +No | +None | +
colormap | +Query (encoded json) | +No | +None | +
cmap = {}
+
+def ColorMapParams(
+ colormap_name: Annotated[ # type: ignore
+ Literal[tuple(cmap.list())],
+ Query(description="Colormap name"),
+ ] = None,
+ colormap: Annotated[
+ Optional[str], Query(description="JSON encoded custom Colormap")
+ ] = None,
+):
+ if colormap_name:
+ return cmap.get(colormap_name)
+
+ if colormap:
+ try:
+ c = json.loads(
+ colormap,
+ object_hook=lambda x: {
+ int(k): parse_color(v) for k, v in x.items()
+ },
+ )
+
+ # Make sure to match colormap type
+ if isinstance(c, Sequence):
+ c = [(tuple(inter), parse_color(v)) for (inter, v) in c]
+
+ return c
+ except json.JSONDecodeError as e:
+ raise HTTPException(
+ status_code=400, detail="Could not parse the colormap value."
+ ) from e
+
+ return None
+
Define input Coordinate Reference System.
+Name | +Type | +Required | +Default | +
---|---|---|---|
crs | +Query (str) | +No | +None | +
def CoordCRSParams(
+ crs: Annotated[
+ Optional[str],
+ Query(
+ alias="coord_crs",
+ description="Coordinate Reference System of the input coords. Default to `epsg:4326`.",
+ ),
+ ] = None,
+) -> Optional[CRS]:
+ """Coordinate Reference System Coordinates Param."""
+ if crs:
+ return CRS.from_user_input(crs)
+
+ return None
+
DatasetParams
¶Overwrite nodata
value, apply rescaling
and change the I/O
or Warp
resamplings.
Name | +Type | +Required | +Default | +
---|---|---|---|
nodata | +Query (str, int, float) | +No | +None | +
unscale | +Query (bool) | +No | +False | +
resampling | +Query (str) | +No | +'nearest' | +
reproject | +Query (str) | +No | +'nearest' | +
@dataclass
+class DatasetParams(DefaultDependency):
+ """Low level WarpedVRT Optional parameters."""
+
+ nodata: Annotated[
+ Optional[Union[str, int, float]],
+ Query(
+ title="Nodata value",
+ description="Overwrite internal Nodata value",
+ ),
+ ] = None
+ unscale: Annotated[
+ bool,
+ Query(
+ title="Apply internal Scale/Offset",
+ description="Apply internal Scale/Offset. Defaults to `False` in rio-tiler.",
+ ),
+ ] = False
+ resampling_method: Annotated[
+ Optional[RIOResampling],
+ Query(
+ alias="resampling",
+ description="RasterIO resampling algorithm. Defaults to `nearest` in rio-tiler.",
+ ),
+ ] = None
+ reproject_method: Annotated[
+ Optional[WarpResampling],
+ Query(
+ alias="reproject",
+ description="WarpKernel resampling algorithm (only used when doing re-projection). Defaults to `nearest` in rio-tiler.",
+ ),
+ ] = None
+
+ def __post_init__(self):
+ """Post Init."""
+ if self.nodata is not None:
+ self.nodata = numpy.nan if self.nodata == "nan" else float(self.nodata)
+
+ if self.unscale is not None:
+ self.unscale = bool(self.unscale)
+
DatasetPathParams
¶Set dataset path.
+Name | +Type | +Required | +Default | +
---|---|---|---|
url | +Query (str) | +Yes | +- | +
def DatasetPathParams(
+ url: Annotated[str, Query(description="Dataset URL")]
+) -> str:
+ """Create dataset path from args"""
+ return url
+
Define output Coordinate Reference System.
+Name | +Type | +Required | +Default | +
---|---|---|---|
crs | +Query (str) | +No | +None | +
def DstCRSParams(
+ crs: Annotated[
+ Optional[str],
+ Query(
+ alias="dst_crs",
+ description="Output Coordinate Reference System.",
+ ),
+ ] = None,
+) -> Optional[CRS]:
+ """Coordinate Reference System Coordinates Param."""
+ if crs:
+ return CRS.from_user_input(crs)
+
+ return None
+
Define numpy's histogram options.
+Name | +Type | +Required | +Default | +
---|---|---|---|
histogram_bins | +Query (encoded list of Number) | +No | +10 | +
histogram_range | +Query (encoded list of Number) | +No | +None | +
@dataclass
+class HistogramParams(DefaultDependency):
+ """Numpy Histogram options."""
+
+ bins: Annotated[
+ Optional[str],
+ Query(
+ alias="histogram_bins",
+ title="Histogram bins.",
+ description="""
+Defines the number of equal-width bins in the given range (10, by default).
+
+If bins is a sequence (comma `,` delimited values), it defines a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform bin widths.
+
+link: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
+ """,
+ openapi_examples={
+ "simple": {
+ "description": "Defines the number of equal-width bins",
+ "value": 8,
+ },
+ "array": {
+ "description": "Defines custom bin edges (comma `,` delimited values)",
+ "value": "0,100,200,300",
+ },
+ },
+ ),
+ ] = None
+
+ range: Annotated[
+ Optional[str],
+ Query(
+ alias="histogram_range",
+ title="Histogram range",
+ description="""
+Comma `,` delimited range of the bins.
+
+The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()).
+
+Values outside the range are ignored. The first element of the range must be less than or equal to the second.
+range affects the automatic bin computation as well.
+
+link: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
+ """,
+ examples="0,1000",
+ ),
+ ] = None
+
+ def __post_init__(self):
+ """Post Init."""
+ if self.bins:
+ bins = self.bins.split(",")
+ if len(bins) == 1:
+ self.bins = int(bins[0]) # type: ignore
+ else:
+ self.bins = list(map(float, bins)) # type: ignore
+ else:
+ self.bins = 10
+
+ if self.range:
+ self.range = list(map(float, self.range.split(","))) # type: ignore
+
ImageRenderingParams
¶Control output image rendering options.
+Name | +Type | +Required | +Default | +
---|---|---|---|
return_mask | +Query (bool) | +No | +False | +
@dataclass
+class ImageRenderingParams(DefaultDependency):
+ """Image Rendering options."""
+
+ add_mask: Annotated[
+ Optional[bool],
+ Query(
+ alias="return_mask",
+ description="Add mask to the output data. Defaults to `True` in rio-tiler",
+ ),
+ ] = None
+
Same as PreviewParams
but without default max_size
.
Name | +Type | +Required | +Default | +
---|---|---|---|
max_size | +Query (int) | +No | +None | +
height | +Query (int) | +No | +None | +
width | +Query (int) | +No | +None | +
@dataclass
+class PartFeatureParams(DefaultDependency):
+ """Common parameters for bbox and feature."""
+
+ max_size: Annotated[Optional[int], "Maximum image size to read onto."] = None
+ height: Annotated[Optional[int], "Force output image height."] = None
+ width: Annotated[Optional[int], "Force output image width."] = None
+
+ def __post_init__(self):
+ """Post Init."""
+ if self.width and self.height:
+ self.max_size = None
+
In titiler.mosaic
, define pixel-selection method to apply.
Name | +Type | +Required | +Default | +
---|---|---|---|
pixel_selection | +Query (str) | +No | +'first' | +
def PixelSelectionParams(
+ pixel_selection: Annotated[ # type: ignore
+ Literal[tuple([e.name for e in PixelSelectionMethod])],
+ Query(description="Pixel selection method."),
+ ] = "first",
+) -> MosaicMethodBase:
+ """
+ Returns the mosaic method used to combine datasets together.
+ """
+ return PixelSelectionMethod[pixel_selection].value()
+
Define image output size.
+Name | +Type | +Required | +Default | +
---|---|---|---|
max_size | +Query (int) | +No | +1024 | +
height | +Query (int) | +No | +None | +
width | +Query (int) | +No | +None | +
@dataclass
+class PreviewParams(DefaultDependency):
+ """Common Preview parameters."""
+
+ max_size: Annotated[int, "Maximum image size to read onto."] = 1024
+ height: Annotated[Optional[int], "Force output image height."] = None
+ width: Annotated[Optional[int], "Force output image width."] = None
+
+ def __post_init__(self):
+ """Post Init."""
+ if self.width and self.height:
+ self.max_size = None
+
RescalingParams
¶Set Min/Max values to rescale from, to 0 -> 255.
+Name | +Type | +Required | +Default | +
---|---|---|---|
rescale | +Query (str, comma delimited Numer) | +No | +None | +
def RescalingParams(
+ rescale: Annotated[
+ Optional[List[str]],
+ Query(
+ title="Min/Max data Rescaling",
+ description="comma (',') delimited Min,Max range. Can set multiple time for multiple bands.",
+ examples=["0,2000", "0,1000", "0,10000"], # band 1 # band 2 # band 3
+ ),
+ ] = None,
+) -> Optional[RescaleType]:
+ """Min/Max data Rescaling"""
+ if rescale:
+ return [tuple(map(float, r.replace(" ", "").split(","))) for r in rescale]
+
+ return None
+
Define options for rio-tiler's statistics method.
+Name | +Type | +Required | +Default | +
---|---|---|---|
categorical | +Query (bool) | +No | +False | +
categories | +Query (list of Number) | +No | +None | +
p | +Query (list of Number) | +No | +[2, 98] | +
@dataclass
+class StatisticsParams(DefaultDependency):
+ """Statistics options."""
+
+ categorical: Annotated[
+ Optional[bool],
+ Query(description="Return statistics for categorical dataset. Defaults to `False` in rio-tiler"),
+ ] = None
+ categories: Annotated[
+ Optional[List[Union[float, int]]],
+ Query(
+ alias="c",
+ title="Pixels values for categories.",
+ description="List of values for which to report counts.",
+ examples=[1, 2, 3],
+ ),
+ ] = None
+ percentiles: Annotated[
+ Optional[List[int]],
+ Query(
+ alias="p",
+ title="Percentile values",
+ description="List of percentile values (default to [2, 98]).",
+ examples=[2, 5, 95, 98],
+ ),
+ ] = None
+
+ def __post_init__(self):
+ """Set percentiles default."""
+ if not self.percentiles:
+ self.percentiles = [2, 98]
+
Defile buffer
and padding
to apply at tile creation.
Name | +Type | +Required | +Default | +
---|---|---|---|
buffer | +Query (float) | +No | +None | +
padding | +Query (int) | +No | +None | +
@dataclass
+class TileParams(DefaultDependency):
+ """Tile options."""
+
+ buffer: Annotated[
+ Optional[float],
+ Query(
+ gt=0,
+ title="Tile buffer.",
+ description="Buffer on each side of the given tile. It must be a multiple of `0.5`. Output **tilesize** will be expanded to `tilesize + 2 * buffer` (e.g 0.5 = 257x257, 1.0 = 258x258).",
+ ),
+ ] = None
+
+ padding: Annotated[
+ Optional[int],
+ Query(
+ gt=0,
+ title="Tile padding.",
+ description="Padding to apply to each tile edge. Helps reduce resampling artefacts along edges. Defaults to `0`.",
+ ),
+ ] = None
+
algorithm.dependency
¶Control which algorithm
to apply to the data.
Name | +Type | +Required | +Default | +
---|---|---|---|
algorithm | +Query (str) | +No | +None | +
algorithm_params | +Query (encoded json) | +No | +None | +
algorithms = {}
+
+def post_process(
+ algorithm: Annotated[
+ Literal[tuple(algorithms.keys())],
+ Query(description="Algorithm name"),
+ ] = None,
+ algorithm_params: Annotated[
+ Optional[str],
+ Query(description="Algorithm parameter"),
+ ] = None,
+) -> Optional[BaseAlgorithm]:
+ """Data Post-Processing options."""
+ kwargs = json.loads(algorithm_params) if algorithm_params else {}
+ if algorithm:
+ try:
+ return algorithms.get(algorithm)(**kwargs)
+
+ except ValidationError as e:
+ raise HTTPException(status_code=400, detail=str(e)) from e
+
+ return None
+
TiTiler's endpoints factories are helper functions that let users create a FastAPI router (fastapi.APIRouter
) with a minimal set of endpoints.
Important
+Most of tiler
Factories are built around rio_tiler.io.BaseReader
, which defines basic methods to access datasets (e.g COG or STAC). The default reader is Reader
for TilerFactory
and MosaicBackend
for MosaicTilerFactory
.
Factories classes use dependencies injection to define most of the endpoint options.
+class: titiler.core.factory.BaseTilerFactory
Most Factories are built from this abstract based class which is used to define commons attributes and utility functions shared between all factories.
+fastapi.APIRouter
.titiler.core.dependencies.DatasetPathParams
.titiler.core.dependencies.BidxExprParams
.nodata
value, apply rescaling
and change the I/O
or Warp
resamplings. Defaults to titiler.core.dependencies.DatasetParams
.algorithm
to apply to the data. Defaults to titiler.core.algorithm.algorithms.dependency
.titiler.core.dependencies.RescalingParams
.titiler.core.dependencies.ColorFormulaParams
.titiler.core.dependencies.ColorMapParams
titiler.core.dependencies.ImageRenderingParams
titiler.core.dependencies.DefaultDependency
lambda: {}
.morecantile.tms
.TileMatrixSet
identifier to use. Defaults to WebMercatorQuad
.""
.OptionalHeader
which endpoints could add (if implemented). Defaults to []
.[]
.[]
.titiler.core.factory.DEFAULT_TEMPLATES
.class: titiler.core.factory.TilerFactory
Factory meant to create endpoints for single dataset using rio-tiler's Reader
.
Reader
./statistics
endpoints. Defaults to titiler.core.dependencies.StatisticsParams
./statistics
endpoints. Defaults to titiler.core.dependencies.HistogramParams
./preview
and /statistics
endpoints. Defaults to titiler.core.dependencies.PreviewParams
./bbox
and /feature
endpoints. Defaults to titiler.core.dependencies.PartFeatureParams
.buffer
and padding
to apply at tile creation. Defaults to titiler.core.dependencies.TileParams
./preview
endpoint to the router. Defaults to True
./bbox
and /feature
endpoints to the router. Defaults to True
./map
endpoints to the router. Defaults to True
.from fastapi import FastAPI
+
+from titiler.core.factory import TilerFactory
+
+# Create FastAPI application
+app = FastAPI()
+
+# Create router and register set of endpoints
+cog = TilerFactory(
+ add_preview=True,
+ add_part=True,
+ add_viewer=True,
+)
+
+# add router endpoint to the main application
+app.include_router(cog.router)
+
Method | +URL | +Output | +Description | +
---|---|---|---|
GET |
+/bounds |
+JSON (Bounds) | +return dataset's bounds | +
GET |
+/info |
+JSON (Info) | +return dataset's basic info | +
GET |
+/info.geojson |
+GeoJSON (InfoGeoJSON) | +return dataset's basic info as a GeoJSON feature | +
GET |
+/statistics |
+JSON (Statistics) | +return dataset's statistics | +
POST |
+/statistics |
+GeoJSON (Statistics) | +return dataset's statistics for a GeoJSON | +
GET |
+/tiles/{tileMatrixSetId}/{z}/{x}/{y}[@{scale}x][.{format}] |
+image/bin | +create a web map tile image from a dataset | +
GET |
+/{tileMatrixSetId}/tilejson.json |
+JSON (TileJSON) | +return a Mapbox TileJSON document | +
GET |
+/{tileMatrixSetId}/WMTSCapabilities.xml |
+XML | +return OGC WMTS Get Capabilities | +
GET |
+/point/{lon},{lat} |
+JSON (Point) | +return pixel values from a dataset | +
GET |
+/preview[.{format}] |
+image/bin | +create a preview image from a dataset Optional | +
GET |
+/bbox/{minx},{miny},{maxx},{maxy}[/{width}x{height}].{format} |
+image/bin | +create an image from part of a dataset Optional | +
POST |
+/feature[/{width}x{height}][.{format}] |
+image/bin | +create an image from a GeoJSON feature Optional | +
GET |
+/{tileMatrixSetId}/map |
+HTML | +return a simple map viewer Optional | +
class: titiler.core.factory.MultiBaseTilerFactory
Custom TilerFactory
to be used with rio_tiler.io.MultiBaseReader
type readers (e.g rio_tiler.io.STACReader
).
MultiBase
Dataset Reader required.titiler.core.dependencies.AssetsBidxExprParams
.titiler.core.dependencies.AssetsParams
.from fastapi import FastAPI
+
+from rio_tiler.io import STACReader # STACReader is a MultiBaseReader
+
+from titiler.core.factory import MultiBaseTilerFactory
+
+app = FastAPI()
+stac = MultiBaseTilerFactory(reader=STACReader)
+app.include_router(stac.router)
+
Method | +URL | +Output | +Description | +
---|---|---|---|
GET |
+/bounds |
+JSON (Bounds) | +return dataset's bounds | +
GET |
+/assets |
+JSON | +return the list of available assets | +
GET |
+/info |
+JSON (Info) | +return assets basic info | +
GET |
+/info.geojson |
+GeoJSON (InfoGeoJSON) | +return assets basic info as a GeoJSON feature | +
GET |
+/asset_statistics |
+JSON (Statistics) | +return per asset statistics | +
GET |
+/statistics |
+JSON (Statistics) | +return assets statistics (merged) | +
POST |
+/statistics |
+GeoJSON (Statistics) | +return assets statistics for a GeoJSON (merged) | +
GET |
+/tiles/{tileMatrixSetId}/{z}/{x}/{y}[@{scale}x][.{format}] |
+image/bin | +create a web map tile image from assets | +
GET |
+/{tileMatrixSetId}/tilejson.json |
+JSON (TileJSON) | +return a Mapbox TileJSON document | +
GET |
+/{tileMatrixSetId}/WMTSCapabilities.xml |
+XML | +return OGC WMTS Get Capabilities | +
GET |
+/point/{lon},{lat} |
+JSON (Point) | +return pixel values from assets | +
GET |
+/preview[.{format}] |
+image/bin | +create a preview image from assets Optional | +
GET |
+/bbox/{minx},{miny},{maxx},{maxy}[/{width}x{height}].{format} |
+image/bin | +create an image from part of assets Optional | +
POST |
+/feature[/{width}x{height}][.{format}] |
+image/bin | +create an image from a geojson feature intersecting assets Optional | +
GET |
+/{tileMatrixSetId}/map |
+HTML | +return a simple map viewer Optional | +
class: titiler.core.factory.MultiBandTilerFactory
Custom TilerFactory
to be used with rio_tiler.io.MultiBandReader
type readers.
MultiBands
Dataset Reader required.titiler.core.dependencies.BandsExprParams
.titiler.core.dependencies.BandsParams
.from fastapi import FastAPI, Query
+
+
+from rio_tiler_pds.landsat.aws import LandsatC2Reader # LandsatC2Reader is a MultiBandReader
+from titiler.core.factory import MultiBandTilerFactory
+
+
+def SceneIDParams(
+ sceneid: Annotated[
+ str,
+ Query(description="Landsat Scene ID")
+ ]
+) -> str:
+ """Use `sceneid` in query instead of url."""
+ return sceneid
+
+
+app = FastAPI()
+landsat = MultiBandTilerFactory(reader=LandsatC2Reader, path_dependency=SceneIDParams)
+app.include_router(landsat.router)
+
Method | +URL | +Output | +Description | +
---|---|---|---|
GET |
+/bounds |
+JSON (Bounds) | +return dataset's bounds | +
GET |
+/bands |
+JSON | +return the list of available bands | +
GET |
+/info |
+JSON (Info) | +return basic info for a dataset | +
GET |
+/info.geojson |
+GeoJSON (InfoGeoJSON) | +return basic info for a dataset as a GeoJSON feature | +
GET |
+/statistics |
+JSON (Statistics) | +return info and statistics for a dataset | +
POST |
+/statistics |
+GeoJSON (Statistics) | +return info and statistics for a dataset | +
GET |
+/tiles/{tileMatrixSetId}/{z}/{x}/{y}[@{scale}x][.{format}] |
+image/bin | +create a web map tile image from a dataset | +
GET |
+/{tileMatrixSetId}/tilejson.json |
+JSON (TileJSON) | +return a Mapbox TileJSON document | +
GET |
+/{tileMatrixSetId}/WMTSCapabilities.xml |
+XML | +return OGC WMTS Get Capabilities | +
GET |
+/point/{lon},{lat} |
+JSON (Point) | +return pixel value from a dataset | +
GET |
+/preview[.{format}] |
+image/bin | +create a preview image from a dataset Optional | +
GET |
+/bbox/{minx},{miny},{maxx},{maxy}[/{width}x{height}].{format} |
+image/bin | +create an image from part of a dataset Optional | +
POST |
+/feature[/{width}x{height}][.{format}] |
+image/bin | +create an image from a geojson feature Optional | +
GET |
+/{tileMatrixSetId}/map |
+HTML | +return a simple map viewer Optional | +
class: titiler.mosaic.factory.MosaicTilerFactory
Endpoints factory for mosaics, built on top of MosaicJSON.
+BaseBackend
Mosaic Reader required.rio_tiler.io.Reader
titiler.core.dependencies.DefaultDependency
pixel_selection
method. Defaults to titiler.mosaic.factory.PixelSelectionParams
.buffer
and padding
to apply at tile creation. Defaults to titiler.core.dependencies.TileParams
.morecantile.tms
.TileMatrixSet
identifier to use. Defaults to WebMercatorQuad
./map
endpoints to the router. Defaults to True
.Method | +URL | +Output | +Description | +
---|---|---|---|
GET |
+/ |
+JSON MosaicJSON | +return a MosaicJSON document | +
GET |
+/bounds |
+JSON (Bounds) | +return mosaic's bounds | +
GET |
+/info |
+JSON (Info) | +return mosaic's basic info | +
GET |
+/info.geojson |
+GeoJSON (InfoGeoJSON) | +return mosaic's basic info as a GeoJSON feature | +
GET |
+/tiles/{tileMatrixSetId}/{z}/{x}/{y}[@{scale}x][.{format}] |
+image/bin | +create a web map tile image from a MosaicJSON | +
GET |
+/{tileMatrixSetId}/tilejson.json |
+JSON (TileJSON) | +return a Mapbox TileJSON document | +
GET |
+/{tileMatrixSetId}/WMTSCapabilities.xml |
+XML | +return OGC WMTS Get Capabilities | +
GET |
+/point/{lon},{lat} |
+JSON (Point) | +return pixel value from a MosaicJSON dataset | +
GET |
+/{z}/{x}/{y}/assets |
+JSON | +return list of assets intersecting a XYZ tile | +
GET |
+/{lon},{lat}/assets |
+JSON | +return list of assets intersecting a point | +
GET |
+/{minx},{miny},{maxx},{maxy}/assets |
+JSON | +return list of assets intersecting a bounding box | +
GET |
+/{tileMatrixSetId}/map |
+HTML | +return a simple map viewer Optional | +
class: titiler.core.factory.TMSFactory
Endpoints factory for OGC TileMatrixSets
.
morecantile.tms
.from fastapi import FastAPI
+
+from titiler.core.factory import TMSFactory
+
+app = FastAPI()
+tms = TMSFactory()
+app.include_router(tms.router)
+
Method | +URL | +Output | +Description | +
---|---|---|---|
GET |
+/tileMatrixSets |
+JSON (TileMatrixSetList) | +retrieve the list of available tiling schemes (tile matrix sets) | +
GET |
+/tileMatrixSets/{tileMatrixSetId} |
+JSON (TileMatrixSet) | +retrieve the definition of the specified tiling scheme (tile matrix set) | +
class: titiler.core.factory.AlgorithmFactory
Endpoints factory for custom algorithms.
+Algorithm
. Defaults to titiler.core.algorithm.algorithms
.from fastapi import FastAPI
+
+from titiler.core.factory import AlgorithmFactory
+
+app = FastAPI()
+algo = AlgorithmFactory()
+app.include_router(algo.router)
+
Method | +URL | +Output | +Description | +
---|---|---|---|
GET |
+/algorithms |
+JSON (Dict of Algorithm Metadata) | +retrieve the list of available Algorithms | +
GET |
+/algorithms/{algorithmId} |
+JSON (Algorithm Metadata) | +retrieve the metadata of the specified algorithm. | +
class: titiler.core.factory.ColorMapFactory
Endpoints factory for colorMaps metadata.
+ColorMaps
. Defaults to rio_tiler.colormap.cmap
.from fastapi import FastAPI
+
+from titiler.core.factory import ColorMapFactory
+
+app = FastAPI()
+colormap = ColorMapFactory()
+app.include_router(colormap.router)
+
Method | +URL | +Output | +Description | +
---|---|---|---|
GET |
+/colorMaps |
+JSON (colorMapList) | +retrieve the list of available colorMaps | +
GET |
+/colorMaps/{colorMapId} |
+JSON (colorMap) | +retrieve the metadata or image of the specified colorMap. | +
Titiler makes use of several great underlying libraries, including GDAL +and Python bindings to GDAL. An effective deployment of titiler +generally requires tweaking GDAL configuration settings. This document provides +an overview of relevant settings. Full documentation from GDAL is available +here.
+GDAL configuration is modified using environment variables. Thus in order to +change a setting you'll need to set environment variables through your +deployment mechanism. For example, in order to test locally you'd set an +environment variable in bash:
+export GDAL_HTTP_MULTIPLEX=YES
+
GDAL_HTTP_MERGE_CONSECUTIVE_RANGES
¶When set to YES
, this tells GDAL to merge adjacent range requests. Instead of
+making two requests for byte ranges 1-5
and 6-10
, it would make a single
+request for 1-10
. This should always be set to YES
.
GDAL_DISABLE_READDIR_ON_OPEN
¶This is a very important setting to control the number of requests GDAL makes.
+This setting has two options: FALSE
and EMPTY_DIR
. FALSE
(the default)
+causes GDAL to try to establish a list of all the available files in the
+directory. EMPTY_DIR
tells GDAL to imagine that the directory is empty except
+for the requested file.
When reading datasets with necessary external sidecar files, it's imperative to
+set FALSE
. For example, the landsat-pds
bucket on AWS S3 contains GeoTIFF
+images where overviews are in external .ovr
files. If set to EMPTY_DIR
, GDAL
+won't find the .ovr
files.
However, in all other cases, it's much better to set EMPTY_DIR
because this
+prevents GDAL from making a LIST
request.
This setting also has cost implications for reading data from requester-pays
+buckets. When set to FALSE
, GDAL makes a LIST
request every time it opens a
+file. Since LIST
requests are much more expensive than GET
requests, this
+can bring unexpected costs.
CPL_VSIL_CURL_ALLOWED_EXTENSIONS
¶A list of file extensions that GDAL is allowed to open. For example if set to
+.tif
, then GDAL would only open files with a .tif
extension. For example, it
+would fail on JPEG2000 files with a .jp2
extension, but also wouldn't open
+GeoTIFFs exposed through an API endpoint that don't have a .tif
suffix.
Note that you also need to include extensions of external overview files. For
+example, the landsat-pds
bucket on AWS S3 has external overviews in .ovr
+files, so if you wished to read this data, you'd want
GDAL_INGESTED_BYTES_AT_OPEN
¶Gives the number of initial bytes GDAL should read when opening a file and +inspecting its metadata.
+Titiler works best with Cloud-Optimized GeoTIFFs (COGs) because they have a +tiled internal structure that supports efficient random reads. These files have +an initial metadata section that describes the location (byte range) within the +file of each internal tile. The more internal tiles the COG has, the more data +the header needs to contain.
+GDAL needs to read the entire header before it can read any other portion of the +file. By default GDAL reads the first 16KB of the file, then if that doesn't +contain the entire metadata, it makes one more request for the rest of the +metadata.
+In environments where latency is relatively high (at least compared to +bandwidth), such as AWS S3, it may be beneficial to increase this value +depending on the data you expect to read.
+There isn't currently a way to get the number of header bytes using GDAL, but
+alternative GeoTIFF readers such as aiocogeo
can. Using its cli
+you can find the image's header size:
export AWS_REQUEST_PAYER="requester"
+aiocogeo info s3://usgs-landsat/collection02/level-2/standard/oli-tirs/2020/072/076/LC08_L2SR_072076_20201203_20210313_02_T2/LC08_L2SR_072076_20201203_20210313_02_T2_SR_B1.TIF
+
+ PROFILE
+ ...
+ Header size: 32770
+
It's wise to inspect the header sizes of your data sources, and set
+GDAL_INGESTED_BYTES_AT_OPEN
appropriately. Beware, however, that the given
+number of bytes will be read for every image, so you don't want to make the
+value too large.
GDAL_CACHEMAX
¶Default GDAL block cache. The value can be either in Mb, bytes or percent of the physical RAM
+Recommended: 200 (200Mb)
+CPL_VSIL_CURL_CACHE_SIZE
¶A global least-recently-used cache shared among all downloaded content and may be reused after a file handle has been closed and reopen
+Recommended: 200000000 (200Mb)
+VSI_CACHE
¶Setting this to TRUE
enables GDAL to use an internal caching mechanism. It's
Recommended (Strongly): TRUE.
+VSI_CACHE_SIZE
¶The size of the above VSI cache in bytes per-file handle. If you open a VRT with 10 files and your VSI_CACHE_SIZE is 10 bytes, the total cache memory usage would be 100 bytes. +The cache is RAM based and the content of the cache is discarded when the file handle is closed.
+Recommended: 5000000 (5Mb per file handle)
+GDAL_BAND_BLOCK_CACHE
¶GDAL Block Cache type: ARRAY
or HASHSET
. See gdal.org/development/rfc/rfc26_blockcache.html
PROJ_NETWORK
¶Introduced with GDAL 3 and PROJ>7, the PROJ library can fetch more precise transformation grids hosted on the cloud.
+Values: ON/OFF
+Ref: proj.org/usage/network.html
+GDAL_HTTP_MULTIPLEX
¶When set to YES
, this attempts to download multiple range requests in
+parallel, reusing the same TCP connection. Note this is only possible when the
+server supports HTTP2, which many servers don't yet support. There's no
+downside to setting YES
here.
GDAL_DATA
¶The GDAL_DATA
variable tells rasterio/GDAL where the GDAL C libraries have been installed. When using rasterio wheels, GDAL_DATA must be unset.
PROJ_LIB
¶The PROJ_LIB
variable tells rasterio/GDAL where the PROJ C libraries have been installed. When using rasterio wheels, PROJ_LIB must be unset.
AWS_REQUEST_PAYER
¶CPL_VSIL_CURL_ALLOWED_EXTENSIONS=".tif,.TIF,.tiff"
In addition to GDAL_DISABLE_READDIR_ON_OPEN
, we set the allowed extensions to .tif
to only enable tif files. (OPTIONAL)
GDAL_CACHEMAX="200"
200 Mb Cache.
+CPL_VSIL_CURL_CACHE_SIZE="200000000
200 Mb VSI Cache.
+GDAL_BAND_BLOCK_CACHE="HASHSET"
GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR"
Maybe the most important variable. Setting it to EMPTY_DIR
reduce the number of GET/LIST requests.
GDAL_HTTP_MERGE_CONSECUTIVE_RANGES="YES"
Tells GDAL to merge consecutive range GET requests.
+GDAL_HTTP_MULTIPLEX="YES"
GDAL_HTTP_VERSION="2"
Both Multiplex and HTTP_VERSION will only have impact if the files are stored in an environment which support HTTP 2 (e.g cloudfront).
+VSI_CACHE="TRUE"
VSI_CACHE_SIZE="5000000"
5Mb cache per file handle.
+ + + + + + + + + + + + + + + + + + + + + +When using Titiler to visualize imagery, there are some helper options that change how the data appears on the screen. You can:
+Color maps are arrays of colors, used to map pixel values to specific colors. For example, it is possible to map a single band DEM, where pixel values denote height, to a color map which shows higher values as white:
+ +Titiler supports both default colormaps (each with a name) and custom color maps.
+Default colormaps pre-made, each with a given name. These maps come from the rio-tiler
library, which has taken colormaps packaged with Matplotlib and has added others that are commonly used with raster data.
A list of available color maps can be found in Titiler's Swagger docs, or in the rio-tiler documentation.
+To use a default colormap, simply use the parameter colormap_name
:
import httpx
+
+resp = httpx.get(
+ "https://titiler.xyz/cog/preview",
+ params={
+ "url": "<YOUR DATASET URL HERE>",
+ "colormap_name": "<YOUR COLORMAP NAME HERE>" # e.g. autumn_r
+ }
+)
+
You can take any of the colormaps listed on rio-tiler
, and add _r
to reverse it.
If you'd like to specify your own colormap, you can specify your own using an encoded JSON:
+import httpx
+
+response = httpx.get(
+ "https://titiler.xyz/cog/preview",
+ params={
+ "url": "<YOUR DATASET URL HERE>",
+ "bidx": "1",
+ "colormap": json.dumps({
+ "0": "#e5f5f9",
+ "10": "#99d8c9",
+ "255": "#2ca25f",
+ })
+ }
+)
+
Titiler supports colormaps that are both discrete (where pixels will be one of the colors that you specify) and linear (where pixel colors will blend between the given colors).
+For more information, please check out rio-tiler's docs.
+It is also possible to add a colormap dependency to automatically apply +a default colormap.
+Color formulae are simple commands that apply color corrections to images. This is useful for reducing artefacts like atmospheric haze, dark shadows, or muted colors.
+Titiler supports color formulae as defined in Mapbox's rio-color
plugin. These include the operations (taken from the rio-color
docs):
Gamma adjustment adjusts RGB values according to a power law, effectively brightening or darkening the midtones. It can be very effective in satellite imagery for reducing atmospheric haze in the blue and green bands.
+Sigmoidal contrast adjustment can alter the contrast and brightness of an image in a way that matches human's non-linear visual perception. It works well to increase contrast without blowing out the very dark shadows or already-bright parts of the image.
+Saturation can be thought of as the "colorfulness" of a pixel. Highly saturated colors are intense and almost cartoon-like, low saturation is more muted, closer to black and white. You can adjust saturation independently of brightness and hue but the data must be transformed into a different color space.
+In Titiler, color_formulae are applied through the color_formula
parameter as a string. An example of this option in action:
import httpx
+
+response = httpx.get(
+ "https://titiler.xyz/cog/preview",
+ params={
+ "url": "<YOUR DATASET URL HERE>",
+ "color_formula": "gamma rg 1.3, sigmoidal rgb 22 0.1, saturation 1.5"
+ }
+)
+
Rescaling is the act of adjusting the minimum and maximum values when rendering an image. In an image with a single band, the rescaled minimum value will be set to black, and the rescaled maximum value will be set to white. This is useful if you want to accentuate features that only appear at a certain pixel value (e.g. you have a DEM, but you want to highlight how the terrain changes between sea level and 100m).
+All titiler endpoinds returning image support rescale
parameter. The parameter should be in form of "rescale={min},{max}"
.
import httpx
+
+response = httpx.get(
+ "https;//titiler.xyz/cog/preview",
+ params={
+ "url": "<YOUR DATASET URL HERE>",
+ "rescale": "0,100",
+ },
+)
+
Titiler supports rescaling on a per-band basis, using multiple rescale
parameters.
import httpx
+
+response = httpx.get(
+ "https;//titiler.xyz/cog/preview",
+ params=(
+ ("url", "<YOUR DATASET URL HERE>"),
+ ("rescale", "0,100"),
+ ("rescale", "0,1000"),
+ ("rescale", "0,10000"),
+ ),
+)
+
By default, Titiler will rescale the bands using the min/max values of the input datatype. For example, PNG images 8- or 16-bit unsigned pixels, +giving a possible range of 0 to 255 or 0 to 65,536, so Titiler will use these ranges to rescale to the output format.
+For certain datasets (e.g. DEMs) this default behaviour can make the image seem washed out (or even entirely one color), +so if you see this happen look into rescaling your images to something that makes sense for your data.
+It is also possible to add a rescaling dependency to automatically apply +a default rescale.
+ + + + + + + + + + + + + + + + + + + + + +Common dependency.
+ + + +dataclass
+
+
+¶
+ Bases: AssetsParams
, BidxParams
Assets, Expression and Asset's band Indexes parameters.
+ +titiler/core/dependencies.py
177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 |
|
dataclass
+
+
+¶
+ Bases: AssetsBidxExprParams
Assets, Expression and Asset's band Indexes parameters but with no requirement.
+ +titiler/core/dependencies.py
239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 |
|
dataclass
+
+
+¶
+ Bases: AssetsParams
, BidxParams
Assets, Asset's band Indexes and Asset's band Expression parameters.
+ +titiler/core/dependencies.py
255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293 +294 +295 +296 +297 +298 +299 +300 +301 +302 +303 +304 +305 +306 +307 +308 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Assets parameters.
+ +titiler/core/dependencies.py
137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 |
|
dataclass
+
+
+¶
+ Bases: ExpressionParams
, BandsParams
Band names and Expression parameters (Band or Expression required).
+ +titiler/core/dependencies.py
342 +343 +344 +345 +346 +347 +348 +349 +350 +351 |
|
dataclass
+
+
+¶
+ Bases: ExpressionParams
, BandsParams
Optional Band names and Expression parameters.
+ +titiler/core/dependencies.py
335 +336 +337 +338 +339 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Band names parameters.
+ +titiler/core/dependencies.py
312 +313 +314 +315 +316 +317 +318 +319 +320 +321 +322 +323 +324 +325 +326 +327 +328 +329 +330 +331 +332 |
|
dataclass
+
+
+¶
+ Bases: ExpressionParams
, BidxParams
Band Indexes and Expression parameters.
+ +titiler/core/dependencies.py
129 +130 +131 +132 +133 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Band Indexes parameters.
+ +titiler/core/dependencies.py
91 + 92 + 93 + 94 + 95 + 96 + 97 + 98 + 99 +100 +101 +102 +103 +104 +105 +106 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Low level WarpedVRT Optional parameters.
+ +titiler/core/dependencies.py
382 +383 +384 +385 +386 +387 +388 +389 +390 +391 +392 +393 +394 +395 +396 +397 +398 +399 +400 +401 +402 +403 +404 +405 +406 +407 +408 +409 +410 +411 +412 +413 +414 +415 +416 +417 +418 +419 +420 +421 |
|
dataclass
+
+
+¶Dataclass with dict unpacking
+ +titiler/core/dependencies.py
66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 |
|
__getitem__(key)
+
Return value.
+ +titiler/core/dependencies.py
78 +79 +80 |
|
Transform dataclass to dict.
+ +titiler/core/dependencies.py
82 +83 +84 +85 +86 +87 |
|
keys()
+
Return Keys.
+ +titiler/core/dependencies.py
70 +71 +72 +73 +74 +75 +76 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Expression parameters.
+ +titiler/core/dependencies.py
109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Numpy Histogram options.
+ +titiler/core/dependencies.py
505 +506 +507 +508 +509 +510 +511 +512 +513 +514 +515 +516 +517 +518 +519 +520 +521 +522 +523 +524 +525 +526 +527 +528 +529 +530 +531 +532 +533 +534 +535 +536 +537 +538 +539 +540 +541 +542 +543 +544 +545 +546 +547 +548 +549 +550 +551 +552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Image Rendering options.
+ +titiler/core/dependencies.py
424 +425 +426 +427 +428 +429 +430 +431 +432 +433 +434 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Common parameters for bbox and feature.
+ +titiler/core/dependencies.py
368 +369 +370 +371 +372 +373 +374 +375 +376 +377 +378 +379 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Common Preview parameters.
+ +titiler/core/dependencies.py
354 +355 +356 +357 +358 +359 +360 +361 +362 +363 +364 +365 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Statistics options.
+ +titiler/core/dependencies.py
470 +471 +472 +473 +474 +475 +476 +477 +478 +479 +480 +481 +482 +483 +484 +485 +486 +487 +488 +489 +490 +491 +492 +493 +494 +495 +496 +497 +498 +499 +500 +501 +502 |
|
dataclass
+
+
+¶
+ Bases: DefaultDependency
Tile options.
+ +titiler/core/dependencies.py
632 +633 +634 +635 +636 +637 +638 +639 +640 +641 +642 +643 +644 +645 +646 +647 +648 +649 +650 +651 +652 |
|
BufferParams(
+ buffer: Annotated[
+ Optional[float],
+ Query(
+ gt=0,
+ title="Tile buffer.",
+ description="Buffer on each side of the given tile. It must be a multiple of `0.5`. Output **tilesize** will be expanded to `tilesize + 2 * buffer` (e.g 0.5 = 257x257, 1.0 = 258x258).",
+ ),
+ ] = None
+) -> Optional[float]
+
Tile buffer Parameter.
+ +titiler/core/dependencies.py
605 +606 +607 +608 +609 +610 +611 +612 +613 +614 +615 +616 |
|
ColorFormulaParams(
+ color_formula: Annotated[
+ Optional[str],
+ Query(
+ title="Color Formula",
+ description="rio-color formula (info: https://github.com/mapbox/rio-color)",
+ ),
+ ] = None
+) -> Optional[str]
+
ColorFormula Parameter.
+ +titiler/core/dependencies.py
619 +620 +621 +622 +623 +624 +625 +626 +627 +628 +629 |
|
CoordCRSParams(
+ crs: Annotated[
+ Optional[str],
+ Query(
+ alias=coord_crs,
+ description="Coordinate Reference System of the input coords. Default to `epsg:4326`.",
+ ),
+ ] = None
+) -> Optional[CRS]
+
Coordinate Reference System Coordinates Param.
+ +titiler/core/dependencies.py
573 +574 +575 +576 +577 +578 +579 +580 +581 +582 +583 +584 +585 +586 |
|
Create dataset path from args
+ +titiler/core/dependencies.py
61 +62 +63 |
|
DstCRSParams(
+ crs: Annotated[
+ Optional[str], Query(alias=dst_crs, description="Output Coordinate Reference System.")
+ ] = None
+) -> Optional[CRS]
+
Coordinate Reference System Coordinates Param.
+ +titiler/core/dependencies.py
589 +590 +591 +592 +593 +594 +595 +596 +597 +598 +599 +600 +601 +602 |
|
RescalingParams(
+ rescale: Annotated[
+ Optional[List[str]],
+ Query(
+ title="Min/Max data Rescaling",
+ description="comma (',') delimited Min,Max range. Can set multiple time for multiple bands.",
+ examples=[(0, 2000), (0, 1000), (0, 10000)],
+ ),
+ ] = None
+) -> Optional[RescaleType]
+
Min/Max data Rescaling
+ +titiler/core/dependencies.py
440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 +453 +454 +455 +456 +457 +458 +459 +460 +461 +462 +463 +464 +465 +466 +467 |
|
create_colormap_dependency(cmap: ColorMaps) -> Callable
+
Create Colormap Dependency.
+ +titiler/core/dependencies.py
19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 |
|
parse asset expression parameters.
+ +titiler/core/dependencies.py
170 +171 +172 +173 +174 |
|
parse_asset_indexes(
+ asset_indexes: Union[Sequence[str], Dict[str, Sequence[int]]]
+) -> Dict[str, Sequence[int]]
+
parse asset indexes parameters.
+ +titiler/core/dependencies.py
160 +161 +162 +163 +164 +165 +166 +167 |
|
Titiler error classes.
+ + + +
+ Bases: TilerError
Bad request error.
+ + +
+ Bases: TilerError
Tile not found error.
+ + +Add exception handlers to the FastAPI app.
+ +TiTiler Router factories.
+ + + +dataclass
+
+
+¶Algorithm endpoints Factory.
+ + + + +dataclass
+
+
+¶BaseTiler Factory.
+Abstract Base Class which defines most inputs used by dynamic tiler.
+ + +Attributes:
+reader
+ (BaseReader
)
+ –
+ A rio-tiler reader (e.g Reader).
+router
+ (APIRouter
)
+ –
+ Application router to register endpoints to.
+path_dependency
+ (Callable
)
+ –
+ Endpoint dependency defining path
to pass to the reader init.
dataset_dependency
+ (DefaultDependency
)
+ –
+ Endpoint dependency defining dataset overwriting options (e.g nodata).
+layer_dependency
+ (DefaultDependency
)
+ –
+ Endpoint dependency defining dataset indexes/bands/assets options.
+render_dependency
+ (DefaultDependency
)
+ –
+ Endpoint dependency defining image rendering options (e.g add_mask).
+colormap_dependency
+ (Callable
)
+ –
+ Endpoint dependency defining ColorMap options (e.g colormap_name).
+process_dependency
+ (DefaultDependency
)
+ –
+ Endpoint dependency defining image post-processing options (e.g rescaling, color-formula).
+tms_dependency
+ (Callable
)
+ –
+ Endpoint dependency defining TileMatrixSet to use.
+reader_dependency
+ (DefaultDependency
)
+ –
+ Endpoint dependency defining BaseReader options.
+environment_dependency
+ (Callable
)
+ –
+ Endpoint dependency to define GDAL environment at runtime.
+router_prefix
+ (str
)
+ –
+ prefix where the router will be mounted in the application.
+optional_headers(sequence
+ (of titiler.core.resources.enums.OptionalHeader
)
+ –
+ additional headers to return with the response.
+add_route_dependencies(*, scopes: List[EndpointScope], dependencies=List[DependsFunc])
+
Add dependencies to routes.
+Allows a developer to add dependencies to a route after the route has been defined.
+ +abstractmethod
+
+
+¶register_routes()
+
Register Tiler Routes.
+ +dataclass
+
+
+¶dataclass
+
+
+¶Factory Extension.
+ + + + +abstractmethod
+
+
+¶register(factory: BaseTilerFactory)
+
Register extension to the factory.
+ +dataclass
+
+
+¶
+ Bases: TilerFactory
Custom Tiler Factory for MultiBandReader classes.
+ + +To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a bands
+argument to most of its methods. By using the BandsExprParams
for the layer_dependency
, the
+.tile(), .point(), .preview() and the .part() methods will receive bands or expression arguments.
The rio_tiler.io.MultiBandReader .info()
and .metadata()
have bands
as
+a requirement arguments (github.com/cogeotiff/rio-tiler/blob/main/rio_tiler/io/base.py#L775).
+This means we have to update the /info and /metadata endpoints in order to add the bands
dependency.
For implementation example see developmentseed/titiler-pds
+dataclass
+
+
+¶
+ Bases: TilerFactory
Custom Tiler Factory for MultiBaseReader classes.
+ + +To be able to use the rio_tiler.io.MultiBaseReader we need to be able to pass a assets
+argument to most of its methods. By using the AssetsBidxExprParams
for the layer_dependency
, the
+.tile(), .point(), .preview() and the .part() methods will receive assets, expression or indexes arguments.
The rio_tiler.io.MultiBaseReader .info()
and .metadata()
have assets
as
+a requirement arguments (github.com/cogeotiff/rio-tiler/blob/main/rio_tiler/io/base.py#L365).
+This means we have to update the /info and /metadata endpoints in order to add the assets
dependency.
dataclass
+
+
+¶TileMatrixSet endpoints Factory.
+ + + + + + +dataclass
+
+
+¶
+ Bases: BaseTilerFactory
Tiler Factory.
+ + +Attributes:
+reader
+ (BaseReader
)
+ –
+ A rio-tiler reader. Defaults to rio_tiler.io.Reader
.
stats_dependency
+ (DefaultDependency
)
+ –
+ Endpoint dependency defining options for rio-tiler's statistics method.
+histogram_dependency
+ (DefaultDependency
)
+ –
+ Endpoint dependency defining options for numpy's histogram method.
+img_preview_dependency
+ (DefaultDependency
)
+ –
+ Endpoint dependency defining options for rio-tiler's preview method.
+img_part_dependency
+ (DefaultDependency
)
+ –
+ Endpoint dependency defining options for rio-tiler's part/feature methods.
+add_preview
+ (bool
)
+ –
+ add /preview
endpoints. Defaults to True.
add_part
+ (bool
)
+ –
+ add /bbox
and /feature
endpoints. Defaults to True.
add_viewer
+ (bool
)
+ –
+ add /map
endpoints. Defaults to True.
register_routes()
+
This Method register routes to the router.
+Because we wrap the endpoints in a class we cannot define the routes as +methods (because of the self argument). The HACK is to define routes inside +the class method and register them after the class initialization.
+ +Titiler middlewares.
+ + + +MiddleWare to add CacheControl in response headers.
+ + + + +async
+
+
+¶__call__(scope: Scope, receive: Receive, send: Send)
+
Handle call.
+ +MiddleWare to add logging.
+ + + + +async
+
+
+¶__call__(scope: Scope, receive: Receive, send: Send)
+
Handle call.
+ +Middleware to make URL parameters case-insensitive. +taken from: tiangolo/fastapi#826
+ + + + +async
+
+
+¶__call__(scope: Scope, receive: Receive, send: Send)
+
Handle call.
+ +__init__(app: ASGIApp) -> None
+
Init Middleware.
+ + +Parameters:
+app
+ (ASGIApp
)
+ –
+ starlette/FastAPI application.
+MiddleWare to add Total process time in response headers.
+ + + + +async
+
+
+¶__call__(scope: Scope, receive: Receive, send: Send)
+
Handle call.
+ +__init__(app: ASGIApp) -> None
+
Init Middleware.
+ + +Parameters:
+app
+ (ASGIApp
)
+ –
+ starlette/FastAPI application.
+OGC models.
+ + + +
+ Bases: BaseModel
Link model.
+Ref: github.com/opengeospatial/ogcapi-tiles/blob/master/openapi/schemas/common-core/link.yaml
+Code generated using koxudaxi/datamodel-code-generator
+ + + + +
+ Bases: BaseModel
TileMatrixSetLink model.
+Based on docs.opengeospatial.org/per/19-069.html#_tilematrixsets
+ + + + +
+ Bases: BaseModel
TileMatrixSetList model.
+Based on docs.opengeospatial.org/per/19-069.html#_tilematrixsets
+ + + + +
+ Bases: BaseModel
TileMatrixSetRef model.
+Based on docs.opengeospatial.org/per/19-069.html#_tilematrixsets
+ + + + +Common response models.
+ + + +
+ Bases: BaseModel
TileJSON model.
+Based on github.com/mapbox/tilejson-spec/tree/master/2.2.0
+ + + + +compute_center()
+
Compute center if it does not exist.
+ +Common response models.
+ + + +
+ Bases: JSONResponse
Custom JSON Response.
+ + + + + + +Custom routing classes.
+ + + +
+ Bases: TypedDict
Define endpoint.
+ + + + +add_route_dependencies(
+ routes: List[BaseRoute], *, scopes: List[EndpointScope], dependencies=List[params.Depends]
+)
+
Add dependencies to routes.
+Allows a developer to add dependencies to a route after the route has been defined.
+ +Create Custom API Route class with custom Env.
+Because we cannot create middleware for specific router we need to create
+a custom APIRoute which add the rasterio.Env(
block before the endpoint is
+actually called. This way we set the env outside the threads and we make sure
+that event multithreaded Reader will get the environment set.
Note: This has been tested in python 3.6 and 3.7 only.
+ +rio-cogeo Extension.
+ + + +dataclass
+
+
+¶
+ Bases: FactoryExtension
Add /validate endpoint to a COG TilerFactory.
+ + + + +register(factory: BaseTilerFactory)
+
Register endpoint to the tiler factory.
+ +rio-stac Extension.
+ + + +
+ Bases: TypedDict
STAC Item.
+ + + + +dataclass
+
+
+¶
+ Bases: FactoryExtension
Add /stac endpoint to a COG TilerFactory.
+ + + + +register(factory: BaseTilerFactory)
+
Register endpoint to the tiler factory.
+ +titiler Viewer Extensions.
+ + + +dataclass
+
+
+¶
+ Bases: FactoryExtension
Add /viewer endpoint to the TilerFactory.
+ + + + +register(factory: BaseTilerFactory)
+
Register endpoint to the tiler factory.
+ +dataclass
+
+
+¶
+ Bases: FactoryExtension
Add /viewer endpoint to the TilerFactory.
+ + + + +register(factory: BaseTilerFactory)
+
Register endpoint to the tiler factory.
+ +Titiler mosaic errors.
+ + + +TiTiler.mosaic Router factories.
+ + + +dataclass
+
+
+¶
+ Bases: BaseTilerFactory
MosaicTiler Factory.
+The main difference with titiler.endpoint.factory.TilerFactory is that this factory
+needs the reader
to be of cogeo_mosaic.backends.BaseBackend
type (e.g MosaicBackend) and a dataset_reader
(BaseReader).
register_routes()
+
This Method register routes to the router.
+Because we wrap the endpoints in a class we cannot define the routes as +methods (because of the self argument). The HACK is to define routes inside +the class method and register them after the class initialization.
+ +PixelSelectionParams(
+ pixel_selection: Annotated[
+ Literal[tuple([name for e in PixelSelectionMethod])],
+ Query(description="Pixel selection method."),
+ ] = "first"
+) -> MosaicMethodBase
+
Returns the mosaic method used to combine datasets together.
+ +