Skip to content

Reject null feature geometries - #1578

Open
draarivpatel-ui wants to merge 3 commits into
developmentseed:mainfrom
draarivpatel-ui:handle-null-feature-geometry
Open

draarivpatel-ui wants to merge 3 commits into
developmentseed:mainfrom
draarivpatel-ui:handle-null-feature-geometry

Conversation

@draarivpatel-ui

Copy link
Copy Markdown
  • return 422 for GeoJSON Features with null geometry in /feature and /statistics
  • cover Feature and FeatureCollection inputs
  • regression tests included

Fixes #1572

Verified with python -m pytest tests/test_factories.py -q in src/titiler/core.

Copilot AI balanced review requested due to automatic review settings November 25, 2026 17:25

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@chuckwondo chuckwondo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add the same check to the four other endpoints that issue #1572 lists. Each still passes model_dump(exclude_none=True) to rio-tiler without it, so a null geometry still returns HTTP 500 from:

  • /statistics in MultiBaseTilerFactory (factory.py)
  • /statistics in MosaicTilerFactory (factory.py)
  • /feature in MosaicTilerFactory (factory.py)
  • /statistics in titiler.xarray's TilerFactory (factory.py)

/feature in MultiBaseTilerFactory is already covered, because it inherits feature_image from TilerFactory. Without the other four, merging will close issue #1572 while they still fail.

Since six endpoints need it, the check could live in one function in titiler.core that each endpoint calls, so the error message is defined once.

These tests cover the four endpoints.

In test_MultiBaseTilerFactory (src/titiler/core/tests/test_factories.py), after the first POST to /statistics:

    # null geometry
    response = client.post(
        f"/statistics?url={DATA_DIR}/item.json&assets=B01&assets=B09",
        json={"type": "Feature", "properties": {}, "geometry": None},
    )

    assert response.status_code == 422

In test_MosaicTilerFactory (src/titiler/mosaic/tests/test_factory.py), with the other /mosaic/feature requests:

        response = client.post(
            "/mosaic/feature",
            params={"url": mosaic_file},
            json={"type": "Feature", "properties": {}, "geometry": None},
        )

        assert response.status_code == 422

In test_mosaic_statistics_featurecollection, after "Test 1":

        # Null geometry
        response = client.post(
            "/mosaic/statistics",
            params={"url": mosaic_file},
            json={"type": "Feature", "properties": {}, "geometry": None},
        )

        assert response.status_code == 422

In src/titiler/xarray/tests/test_factory.py, after test_statistics:

def test_statistics_null_geometry(app):
    """A Feature with a null geometry gets HTTP 422, not a server error."""
    resp = app.post(
        "/md/statistics",
        params={"url": dataset_2d_nc, "variable": "dataset"},
        json={"type": "Feature", "properties": {}, "geometry": None},
    )

    assert resp.status_code == 422

fc = FeatureCollection(type="FeatureCollection", features=[geojson])

if any(feature.geometry is None for feature in fc.features):
raise HTTPException(status_code=422, detail="Invalid geometry")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make this message name the feature that has no geometry, and say that the endpoint needs one. "Invalid geometry" is the text of the rio-tiler error behind the old HTTP 500, so a client gets the same message as before, now with a 422. It also calls the geometry invalid, although GeoJSON allows a null geometry (RFC 7946, Section 3.2). And for a FeatureCollection, it does not say which feature to fix.

For example, the shared function from the review body could live in titiler.core.utils, which titiler.mosaic and titiler.xarray already import:

def require_geometries(geojson: Feature | FeatureCollection) -> None:
    """Raise HTTP 422 if a Feature in the GeoJSON body has a null geometry."""
    if isinstance(geojson, Feature):
        if geojson.geometry is None:
            raise HTTPException(
                status_code=422,
                detail="Feature has a null 'geometry'; this endpoint needs a geometry.",
            )
        return

    for i, feature in enumerate(geojson.features):
        if feature.geometry is None:
            raise HTTPException(
                status_code=422,
                detail=f"features[{i}] has a null 'geometry'; "
                "this endpoint needs a geometry for every feature.",
            )

Call it first in each endpoint. In /statistics, that puts it before the body is wrapped in a FeatureCollection, so a client that sent a single Feature is not told about features[0].

Comment on lines +547 to +550
response = client.post(
f"/statistics?url={DATA_DIR}/cog.tif&bidx=1&bidx=1&bidx=1", json=null_feature
)
assert response.status_code == 422

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also post a FeatureCollection: the description says the tests cover one, but both new requests send a single Feature. Asserting the message keeps it naming the feature (wording from the comment on factory.py):

Suggested change
response = client.post(
f"/statistics?url={DATA_DIR}/cog.tif&bidx=1&bidx=1&bidx=1", json=null_feature
)
assert response.status_code == 422
response = client.post(
f"/statistics?url={DATA_DIR}/cog.tif&bidx=1&bidx=1&bidx=1", json=null_feature
)
assert response.status_code == 422
assert response.json() == {
"detail": "Feature has a null 'geometry'; this endpoint needs a geometry."
}
response = client.post(
f"/statistics?url={DATA_DIR}/cog.tif",
json={"type": "FeatureCollection", "features": [feature, null_feature]},
)
assert response.status_code == 422
assert response.json() == {
"detail": "features[1] has a null 'geometry'; "
"this endpoint needs a geometry for every feature."
}

…points

Apply the shared require_geometries check to every endpoint that passes
a GeoJSON body to rio-tiler: /statistics in the core, mosaic and xarray
factories, and /feature in the core and mosaic factories. Null
geometries are valid per RFC 7946 but cannot be rasterized, so answer
HTTP 422 with a message naming the offending feature instead of failing
with HTTP 500 inside rio-tiler.
geojson: Annotated[
FeatureCollection | Feature,
Body(description="GeoJSON Feature or FeatureCollection."),
],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it will be cleaner to add a validator directly in the endpoint dependencies

see

@dataclass
class AssetsParams(DefaultDependency):
"""Assets parameters."""
assets: Annotated[
list[str],
AfterValidator(_parse_asset),
Query(
title="Asset names",
description="Asset's names.",
openapi_examples={
"user-provided": {"value": None},
"one-asset": {
"description": "Return results for asset `data`.",
"value": ["data"],
},
"multi-assets": {
"description": "Return results for assets `data` and `cog`.",
"value": ["data", "cog"],
},
"multi-assets-with-options": {
"description": "Return results for assets `data` and `cog`.",
"value": ["data|bidx=1", "cog|bidx=1,2"],
},
},
),
]

https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#custom-validation

@chuckwondo chuckwondo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make two changes to how the check is attached: have require_geometries raise ValueError, and define the geojson parameter types once instead of in each endpoint.

Raise ValueError. A pydantic validator reports a failure by raising ValueError, as in FastAPI's custom validation example and in every validator in titiler.core.validation. FastAPI then answers 422 in its usual format, a list of errors under detail, as it already does for a malformed geometry or rescale=foo. An HTTPException raised inside the validator bypasses that, in two ways:

  • detail is a string for this one error and a list for every other invalid input, so a client that reads the list breaks on it.
  • FastAPI drops the other errors in the request. With a null-geometry Feature, POST /statistics?url=...&bidx=abc reports only the geometry, not the bad bidx.

The message text stays as it is, and pydantic puts Value error, in front of it. Because every function in titiler.core.validation is a validator that raises ValueError, require_geometries fits there, which also leaves utils.py as it is on main:

def require_geometries(
    geojson: Feature | FeatureCollection,
) -> Feature | FeatureCollection:
    """Reject a GeoJSON body in which a Feature has a null geometry."""
    if isinstance(geojson, Feature):
        if geojson.geometry is None:
            raise ValueError(
                "Feature has a null 'geometry'; this endpoint needs a geometry."
            )
        return geojson

    for i, feature in enumerate(geojson.features):
        if feature.geometry is None:
            raise ValueError(
                f"features[{i}] has a null 'geometry'; "
                "this endpoint needs a geometry for every feature.",
            )

    return geojson

The two message assertions in test_TilerFactory then become:

    assert response.json()["detail"][0]["msg"] == (
        "Value error, Feature has a null 'geometry'; this endpoint needs a geometry."
    )
    assert response.json()["detail"][0]["msg"] == (
        "Value error, features[1] has a null 'geometry'; "
        "this endpoint needs a geometry for every feature."
    )

Define the parameter types once. Each endpoint now repeats the same Annotated[...] block, in two shapes:

With one definition per shape, the check is attached in one place, and a new endpoint that takes the shared type gets it too. dependencies.py already defines a shared Annotated type, ZoomsStr, imports from titiler.core.validation, and is imported by all three factories. After its imports:

GeoJSONBody = Annotated[
    FeatureCollection | Feature,
    Body(description="GeoJSON Feature or FeatureCollection."),
    AfterValidator(require_geometries),
]

FeatureBody = Annotated[
    Feature,
    Body(description="GeoJSON Feature."),
    AfterValidator(require_geometries),
]

This needs Body added to its fastapi import, require_geometries added to its titiler.core.validation import, and from geojson_pydantic.features import Feature, FeatureCollection.

Each endpoint's parameter then becomes geojson: GeoJSONBody, or geojson: FeatureBody,, and the three factories no longer import Body, AfterValidator, or require_geometries.

The four endpoints, the message, and the FeatureCollection test from the earlier review are all in.

return Polygon.from_bounds(*bounds)


def require_geometries(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rename this require_geojson_geometries

@vincentsarago

Copy link
Copy Markdown
Member

@draarivpatel-ui would you have time to finish this PR this week?

This branch was successfully deployed

1 active deployment
ci — 83c844ef Deployed Nov 26, 2026 by draarivpatel-ui via tests (3.11) #212
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

POST /statistics and /feature return HTTP 500 for a Feature whose geometry is null

4 participants