Debian Codegraph @

docs/src/intro.md

raw symbols SCIP
1
2 ## Usage
3
4 ```python
5 from geojson_pydantic import Feature, FeatureCollection, Point
6
7 geojson_feature = {
8 "type": "Feature",
9 "geometry": {
10 "type": "Point",
11 "coordinates": [13.38272, 52.46385],
12 },
13 "properties": {
14 "name": "jeff",
15 },
16 }
17
18
19 feat = Feature(**geojson_feature)
20 assert feat.type == "Feature"
21 assert type(feat.geometry) == Point
22 assert feat.properties["name"] == "jeff"
23
24 fc = FeatureCollection(type="FeatureCollection", features=[geojson_feature, geojson_feature])
25 assert fc.type == "FeatureCollection"
26 assert len(fc.features) == 2
27 assert type(fc.features[0].geometry) == Point
28 assert fc.features[0].properties["name"] == "jeff"
29 ```
30
31 ## Geometry Model methods and properties
32
33 - `__geo_interface__`: GeoJSON-like protocol for geo-spatial (GIS) vector data ([spec](https://gist.github.com/sgillies/2217756#__geo_interface)).
34 - `has_z`: returns true if any coordinate has a Z value.
35 - `wkt`: returns the Well Known Text representation of the geometry.
36 - `create`: create a geometry object without providing the `type` information
37
38 ##### For Polygon geometry
39
40 - `exterior`: returns the exterior Linear Ring of the polygon.
41 - `interiors`: returns the interiors (Holes) of the polygon.
42 - `Polygon.from_bounds(xmin, ymin, xmax, ymax)`: creates a Polygon geometry from a bounding box.
43
44 ##### For GeometryCollection and FeatureCollection
45
46 - `iter()`: iterates over geometries or features
47 - `length`: returns geometries or features count
48
49 ## Advanced usage
50
51 In `geojson_pydantic` we've implemented pydantic's [Generic Models](https://pydantic-docs.helpmanual.io/usage/models/#generic-models) which allow the creation of more advanced models to validate either the geometry type or the properties.
52
53 In order to make use of this generic typing, there are two steps: first create a new model, then use that model to validate your data. To create a model using a `Generic` type, you **HAVE TO** pass `Type definitions` to the `Feature` model in form of `Feature[Geometry Type, Properties Type]`. Then pass your data to this constructor.
54
55 By default `Feature` and `FeatureCollections` are defined using `geojson_pydantic.geometries.Geometry` for the geometry and `typing.Dict` for the properties.
56
57 Here's an example where we want to validate that GeoJSON features have Polygon types, but don't do any specific property validation.
58
59 ```python
60 from typing import Dict
61
62 from geojson_pydantic import Feature, Polygon
63 from pydantic import BaseModel
64
65 geojson_feature = {
66 "type": "Feature",
67 "geometry": {
68 "type": "Point",
69 "coordinates": [13.38272, 52.46385],
70 },
71 "properties": {
72 "name": "jeff",
73 },
74 }
75
76 # Define a Feature model with Geometry as `Polygon` and Properties as `Dict`
77 MyPolygonFeatureModel = Feature[Polygon, Dict]
78
79 feat = MyPolygonFeatureModel(**geojson_feature) # should raise Validation Error because `geojson_feature` is a point
80 >>> ValidationError: 3 validation errors for Feature[Polygon, Dict]
81 ...
82 geometry -> type
83 unexpected value; permitted: 'Polygon' (type=value_error.const; given=Point; permitted=['Polygon'])
84
85
86 geojson_feature = {
87 "type": "Feature",
88 "geometry": {
89 "type": "Polygon",
90 "coordinates": [
91 [
92 [13.38272, 52.46385],
93 [13.42786, 52.46385],
94 [13.42786, 52.48445],
95 [13.38272, 52.48445],
96 [13.38272, 52.46385],
97 ]
98 ],
99 },
100 "properties": {
101 "name": "jeff",
102 },
103 }
104
105 feat = MyPolygonFeatureModel(**geojson_feature)
106 assert type(feat.geometry) == Polygon
107 ```
108
109 Or with optional geometry
110
111 ```python
112 from geojson_pydantic import Feature, Point
113 from typing import Optional
114
115 MyPointFeatureModel = Feature[Optional[Point], Dict]
116
117 assert MyPointFeatureModel(type="Feature", geometry=None, properties={}).geometry is None
118 assert MyPointFeatureModel(type="Feature", geometry=Point(type="Point", coordinates=(0,0)), properties={}).geometry is not None
119 ```
120
121 And now with constrained properties
122
123 ```python
124 from typing_extensions import Annotated
125 from geojson_pydantic import Feature, Point
126 from pydantic import BaseModel
127
128 # Define a Feature model with Geometry as `Point` and Properties as a constrained Model
129 class MyProps(BaseModel):
130 name: Annotated[str, Field(pattern=r"^(drew|vincent)$")]
131
132 MyPointFeatureModel = Feature[Point, MyProps]
133
134 geojson_feature = {
135 "type": "Feature",
136 "geometry": {
137 "type": "Point",
138 "coordinates": [13.38272, 52.46385],
139 },
140 "properties": {
141 "name": "jeff",
142 },
143 }
144
145 feat = MyPointFeatureModel(**geojson_feature)
146 >>> ValidationError: 1 validation error for Feature[Point, MyProps]
147 properties -> name
148 string does not match regex "^(drew|vincent)$" (type=value_error.str.regex; pattern=^(drew|vincent)$)
149
150 geojson_feature["properties"]["name"] = "drew"
151 feat = MyPointFeatureModel(**geojson_feature)
152 assert feat.properties.name == "drew"
153 ```
154
155 ## Enforced `type` Keys
156
157 Starting with version `0.6.0`, geojson-pydantic's classes will not define default keys such has `type`, `geometry` or `properties`.
158 This is to make sure the library does well its first goal, which is `validating` GeoJSON object based on the [specification](https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.1)
159
160 o A GeoJSON object has a member with the name "type". The value of
161 the member MUST be one of the GeoJSON types.
162
163 o A Feature object HAS a "type" member with the value "Feature".
164
165 o A Feature object HAS a member with the name "geometry". The value
166 of the geometry member SHALL be either a Geometry object as
167 defined above or, in the case that the Feature is unlocated, a
168 JSON null value.
169
170 o A Feature object HAS a member with the name "properties". The
171 value of the properties member is an object (any JSON object or a
172 JSON null value).
173
174
175 ```python
176 from geojson_pydantic import Point
177
178 ## Before 0.6
179 Point(coordinates=(0,0))
180 >> Point(type='Point', coordinates=(0.0, 0.0), bbox=None)
181
182 ## After 0.6
183 Point(coordinates=(0,0))
184 >> ValidationError: 1 validation error for Point
185 type
186 field required (type=value_error.missing)
187
188 Point(type="Point", coordinates=(0,0))
189 >> Point(type='Point', coordinates=(0.0, 0.0), bbox=None)
190 ```
191
192 Starting with `2.1.0`, users can use the `.create()` methods to create geometries without the `type` information
193
194 ```python
195 from geojson_pydantic import Point
196
197 Point.create(coordinates=(0,0))
198 # is equivalent to
199 Point(bbox=None, type='Point', coordinates=Position2D(longitude=0.0, latitude=0.0))
200 ```