Pydantic GeoJSON Models
geojson-pydantic provides a suite of Pydantic models that strictly adhere to the GeoJSON specification (RFC 7946). These models are invaluable for creating, validating, and working with GeoJSON data in a type-safe manner. The library is actively maintained, supporting Python 3.9 and above, with a consistent release cadence that includes performance improvements and Pydantic V2 compatibility.
Warnings
- breaking Migration to Pydantic V2.0: geojson-pydantic versions 1.0 and above require Pydantic V2.0+. This involves significant breaking changes from Pydantic V1, including method renames like `dict()` to `model_dump()`, `json()` to `model_dump_json()`, and `parse_obj()` to `model_validate()`. Older geojson-pydantic versions (e.g., <=0.6.3) are incompatible with Pydantic V2.
- breaking Removed custom iteration, length, and item access for `GeometryCollection` and `FeatureCollection`: Version 2.0.0 removed custom `__iter__`, `__getitem__`, and `__len__` methods. Direct iteration or `len()` calls on these objects will now fail.
- breaking Changed generic typing for `FeatureCollection`: From version 1.0, the generic `FeatureCollection` model now expects a generic `Feature` model. The type hint has changed from `FeatureCollection[Geometry, Properties]` to `FeatureCollection[Feature[Geometry, Properties]]`.
- gotcha Missing 'type' attribute when creating GeoJSON objects: All GeoJSON objects require a 'type' attribute (e.g., 'Point', 'Feature', 'Polygon') as part of their data structure, which is then validated by geojson-pydantic. Omitting this will lead to validation errors.
Install
-
pip install geojson-pydantic
Imports
- Point
from geojson_pydantic import Point
- Feature
from geojson_pydantic import Feature
- FeatureCollection
from geojson_pydantic import FeatureCollection
- GeometryCollection
from geojson_pydantic import GeometryCollection
Quickstart
from geojson_pydantic import Feature, Point
# Define a GeoJSON Point object data
geoj_point_data = {
"type": "Point",
"coordinates": [-105.01621, 39.57422]
}
# Create a Pydantic Point model instance
point_obj = Point(**geoj_point_data)
print(f"Point Object: {point_obj.model_dump_json()}")
# Define a GeoJSON Feature object data
geoj_feature_data = {
"type": "Feature",
"geometry": geoj_point_data, # Use the previously defined point data
"properties": {"name": "Example Feature", "value": 123}
}
# Create a Pydantic Feature model instance
feature_obj = Feature(**geoj_feature_data)
print(f"Feature Object: {feature_obj.model_dump_json()}")