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.
pip install geojson-pydanticVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to create a simple GeoJSON Point and Feature object using geojson-pydantic, validating and serializing them to JSON. Note the use of `model_dump_json()` for serialization with Pydantic V2.
Upgrade Pydantic to V2 and update your code to use the new `model_` prefixed methods. For instance, `my_model.json()` becomes `my_model.model_dump_json()`. Review Pydantic's official migration guide for V1 to V2 changes.
For iteration, use the `.iter()` method (e.g., `for geom in collection.iter()`). For length, use the `.length` property (e.g., `collection.length`). For item access, access the underlying lists directly (e.g., `collection.geometries[0]` or `collection.features[0]`).
Update generic type hints for `FeatureCollection` to nest the `Feature` type. For example, if you had `MyFc = FeatureCollection[Polygon, CustomProperties]`, it should now be `MyFc = FeatureCollection[Feature[Polygon, CustomProperties]]`.
Always include the mandatory 'type' field with the correct GeoJSON object type string when constructing data for geojson-pydantic models. For example: `Point(type="Point", coordinates=[...])`.
Correct the GeoJSON data to adhere to the specification; for instance, ensure longitude values are within [-180, 180] and latitude values within [-90, 90], and all mandatory fields (like 'type' and 'coordinates' for Point) are present and correctly typed.
Migrate the method calls to their Pydantic V2 equivalents: use `model_dump()` instead of `dict()`, `model_dump_json()` instead of `json()`, and `model_validate()` instead of `parse_obj()` or `parse_raw()`.
Instantiate the `geojson-pydantic` model with your dictionary (e.g., `point_model = PointModel(**my_data)`) before using dot notation, or use dictionary-style key access (e.g., `my_data['type']`) if you intend to work with a dictionary.
To make model instances hashable, configure `frozen=True` within the model's `model_config` (e.g., `class Config: frozen = True` in Pydantic V1, or `model_config = ConfigDict(frozen=True)` in Pydantic V2). Alternatively, convert the model to an immutable, hashable representation if appropriate for the use case.
Use `model_instance.model_dump_json()` to serialize a geojson-pydantic model to a JSON string, or `model_instance.model_dump()` to get a dictionary representation.