catastrogps 2.0.0__tar.gz → 2.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- catastrogps-2.2.0/CHANGELOG.md +58 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/PKG-INFO +34 -6
- {catastrogps-2.0.0 → catastrogps-2.2.0}/README.md +33 -5
- {catastrogps-2.0.0 → catastrogps-2.2.0}/catastrogps/__init__.py +2 -0
- catastrogps-2.2.0/catastrogps/_version.py +1 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/catastrogps/client.py +6 -1
- catastrogps-2.2.0/catastrogps/locations.py +39 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/catastrogps/parcels.py +41 -2
- {catastrogps-2.0.0 → catastrogps-2.2.0}/pyproject.toml +1 -1
- {catastrogps-2.0.0 → catastrogps-2.2.0}/tests/test_client.py +7 -0
- catastrogps-2.2.0/tests/test_sigpac.py +221 -0
- catastrogps-2.2.0/tests/test_subparcels_and_locations.py +291 -0
- catastrogps-2.0.0/catastrogps/_version.py +0 -1
- {catastrogps-2.0.0 → catastrogps-2.2.0}/.gitignore +0 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/LICENSE +0 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/catastrogps/errors.py +0 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/catastrogps/export.py +0 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/catastrogps/fincas.py +0 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/catastrogps/py.typed +0 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/tests/__init__.py +0 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/tests/test_analysis.py +0 -0
- {catastrogps-2.0.0 → catastrogps-2.2.0}/tests/test_fincas.py +0 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 2.2.0 (2026-10-23)
|
|
4
|
+
|
|
5
|
+
- `parcels.sigpac(ref, country=, lang=)`: `GET /v1/parcels/{ref}/sigpac`, every SIGPAC enclosure of a Spanish parcel (ES, PV, NA) with land use, irrigation, slope, altitude, CAP eligibility and region, incidents and outline. 1 unit, 0 when empty; `SIG_001` raises `ServiceUnavailableError`, retried and not charged.
|
|
6
|
+
- `parcels.sigpac_geojson(ref, country=, lang=)`: the same with `format=geojson`, parsed into a GeoJSON FeatureCollection dict.
|
|
7
|
+
- README: subparcels coverage lists every country the API answers (adds DE, CZ, NL, FR, PT, SE, CH, FI, BE, IE, SI).
|
|
8
|
+
|
|
9
|
+
## 2.1.0 (2026-10-21)
|
|
10
|
+
|
|
11
|
+
- `parcels.subparcels(ref, country=, lang=)`: `GET /v1/parcels/{ref}/subparcels`, crops and land use of each part of the parcel (`cropCode`, `crop`, `cropOriginal`, `intensity`, `area`, `landType`, `landClass`, `kind`, `useClass`, `useClassName`, `source`, `geometry`). Paid (1 unit, 0 when empty); a source failure raises `ServiceUnavailableError` with code `SUB_001` and is not charged.
|
|
12
|
+
- The parcel answer no longer carries `subparcels`: it has `subparcelCount` and `cropSummary`. Subparcel `landGrade` is now `cropCode`.
|
|
13
|
+
- `parcels.get(ref, lang=)` and `crop_catalog(lang=)` (`GET /v1/reference/crops`, free): crop names in es, ca, en, pt, fr, it, de, pl, nl or cs (`CROP_LANGUAGES`).
|
|
14
|
+
- `parcels.neighbors(ref, country=)`: `GET /v1/parcels/{ref}/neighbors`.
|
|
15
|
+
- `client.locations.provinces()`, `municipalities(region)`, `streets(region, municipality, name=)`: Spanish address helpers under `/v1/locations`.
|
|
16
|
+
- `parcels.market` documents `zonePrices` (official province prices in Spain).
|
|
17
|
+
- README: the coordinates example used the old Spanish keys, and DXF is no longer listed (v1 exports KML and GPX).
|
|
18
|
+
|
|
19
|
+
## 2.0.0 (2026-10-20)
|
|
20
|
+
|
|
21
|
+
- Breaking: every call goes to the English v1 API (`https://api.parcelgps.com/v1/...`). The Spanish-named `/api` routes that 1.x used still answer but are deprecated.
|
|
22
|
+
- Breaking: response dicts use English camelCase keys (`reference`, `country`, `address`, `municipality`, `region`, `latitude`, `longitude`, `parcelArea`, `builtArea`, `yearBuilt`, `polygon`...). `get_units` returns `units`, `constructions` and `propertyUnitCount`; `search_address_candidates` returns `query` and `candidates`; terrain and ground motion keys are camelCase (`protectedAreas`, `groundMotion.vertical.meanMmYear`).
|
|
23
|
+
- `parcels.agriculture` calls `/v1/parcels/{ref}/agriculture` and returns the English block directly.
|
|
24
|
+
- `find_by_address` sends `{"address": ...}`; `compare` sends `{"parcels": [{"reference", "country"}]}`; `export.file` sends `reference` and supports `kml` and `gpx` only.
|
|
25
|
+
- Errors read the v1 body `{code, message, details}` (the legacy `{error, data}` is still understood).
|
|
26
|
+
- Default `base_url` is `https://api.parcelgps.com`.
|
|
27
|
+
|
|
28
|
+
## 1.3.2
|
|
29
|
+
|
|
30
|
+
- README and package description state the coverage like the website: 29 European countries, including the Basque Country and Navarre foral cadastres; by cadastral reference in 27 and by coordinates in all 29. The "31 official cadastres" count is gone.
|
|
31
|
+
|
|
32
|
+
## 1.3.1
|
|
33
|
+
|
|
34
|
+
- README and package description state the coverage with the real numbers: 29 European countries, 31 official cadastres including the Basque Country and Navarre.
|
|
35
|
+
|
|
36
|
+
## 1.3.0
|
|
37
|
+
|
|
38
|
+
- `parcels.terrain(ref, country=, lat=, lng=)`: relief (Copernicus DEM), Natura 2000 and national protected areas (EEA) and ERA5-Land climate normals. `lat`/`lng` are needed outside ES, PV, NA, PT, FR, IT and DE.
|
|
39
|
+
- `parcels.ground_motion(ref, country=, lat=, lng=)`: Copernicus EGMS subsidence or uplift in mm/year (2020-2024).
|
|
40
|
+
- `parcels.market`, `parcels.score`, `parcels.value_history` and `parcels.compare`: the analysis endpoints that now accept an API key.
|
|
41
|
+
- `search_address_candidates(country=)`: address search in Spain and 26 more countries.
|
|
42
|
+
- `get_units(ref, country="PV" | "NA")`: building units from the Basque and Navarre foral cadastres.
|
|
43
|
+
- Quota: `last_quota["overage"]` (prepaid balance, unit price, units it still covers), `last_quota["rate_limit"]` (per-minute burst) and `last_quota["finca_cap"]` (contract cap on `/units`); `conditional_request` and every units page return the quota of that response. The monthly keys no longer fall back to the per-minute headers, and absent keys are left out instead of `None`.
|
|
44
|
+
- `QuotaExceededError.quota` and `prepaid_balance_empty`; `PlaceNameError` for `CNV_PLACE_NAME` with the geocoded `location`; `CoverageError.country`, `feature` and `supported_countries`.
|
|
45
|
+
- `typing_extensions` is now a declared dependency (it was imported without being declared).
|
|
46
|
+
- README: honest coverage table (26 cadastres, Germany without Bavaria, Portugal without Lisbon, Porto and Coimbra), units cost one quota unit per unit, foral units supported.
|
|
47
|
+
|
|
48
|
+
## 1.2.0
|
|
49
|
+
|
|
50
|
+
- `get_units(refcat14, previous=None)`: every unit of a Spanish finca, following `nextCursor`, with `totalUnidadesFinca`, `dataSource`, `dataDate`, `attribution` and `construcciones`. Re-imports send `If-None-Match` per page and reuse unchanged pages (`changed: False`).
|
|
51
|
+
- `iter_unit_pages(refcat14)`: the same, page by page.
|
|
52
|
+
- `search_address_candidates(q, street=, number=, municipality=, postcode=, limit=)`: address to finca candidates ranked by confidence.
|
|
53
|
+
- `ServiceUnavailableError.retry_after`, honoured by the retry loop (capped at 60 s).
|
|
54
|
+
- `client.fincas` resource and `conditional_request` for 304-aware calls.
|
|
55
|
+
|
|
56
|
+
## 1.1.2
|
|
57
|
+
|
|
58
|
+
- Monthly quota read from `X-Quota-*` headers.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: catastrogps
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.2.0
|
|
4
4
|
Summary: Official Python client for the Catastro GPS API: parcels from 29 European countries (including the Basque Country and Navarre foral cadastres) by reference, coordinates or address; building units, terrain, ground motion, solar and more
|
|
5
5
|
Project-URL: Homepage, https://www.parcelgps.com/developers
|
|
6
6
|
Project-URL: Documentation, https://www.parcelgps.com/developers
|
|
@@ -36,7 +36,9 @@ Official Python client for the [Catastro GPS API](https://www.parcelgps.com/deve
|
|
|
36
36
|
- Look up a parcel by its **official cadastral reference** or by **coordinates**, with the country detected for you.
|
|
37
37
|
- Turn a **postal address into parcels** in Spain and 26 more countries, ranked by confidence.
|
|
38
38
|
- Import **every unit of a Spanish building** (dwellings, shops, garages) with paging and free `304` refreshes.
|
|
39
|
-
- Get the **parcel outline** (GeoJSON or a `[lat, lng]` ring),
|
|
39
|
+
- Get the **parcel outline** (GeoJSON or a `[lat, lng]` ring), **KML / GPX** exports and the **adjoining parcels**.
|
|
40
|
+
- **Crops and land use of each part of a parcel** (Spain with the foral territories, Austria, Estonia, Greece), with crop names in 10 languages and a free crop code catalogue.
|
|
41
|
+
- **Spanish provinces, municipalities and streets** to build a structured address search.
|
|
40
42
|
- **Relief, Natura 2000 and climate** (Copernicus DEM, EEA, ERA5-Land) and **ground motion** (Copernicus EGMS, mm/year) for any covered country.
|
|
41
43
|
- **Solar**, **agriculture**, **market**, **score**, **value history** and **comparison** for Spain, Portugal, France, Italy and Germany.
|
|
42
44
|
- Quota, prepaid balance and per-minute limit of every response, typed exceptions for every API code.
|
|
@@ -72,7 +74,11 @@ with CatastroGPS() as client:
|
|
|
72
74
|
|
|
73
75
|
| Method | Endpoint | Countries |
|
|
74
76
|
|--------|----------|-----------|
|
|
75
|
-
| `parcels.get(ref, country=)` | `GET /v1/parcels/{ref}` | All references (see coverage) |
|
|
77
|
+
| `parcels.get(ref, country=, lang=)` | `GET /v1/parcels/{ref}` | All references (see coverage). Carries `subparcelCount` and `cropSummary` |
|
|
78
|
+
| `parcels.subparcels(ref, country=, lang=)` | `GET /v1/parcels/{ref}/subparcels` | ES (with PV/NA), AT, DE, CZ, NL, FR, PT, SE, CH, FI, BE, IE, SI, EE, GR. 1 unit; 0 when the parcel has none |
|
|
79
|
+
| `parcels.sigpac(ref, country=, lang=)` | `GET /v1/parcels/{ref}/sigpac` | ES, PV, NA. SIGPAC enclosures with land use, irrigation, slope, CAP eligibility, incidents and outline. 1 unit; 0 when there are none; `SIG_001` is not charged |
|
|
80
|
+
| `parcels.sigpac_geojson(ref, country=, lang=)` | `GET /v1/parcels/{ref}/sigpac?format=geojson` | The same as a GeoJSON FeatureCollection (dict) |
|
|
81
|
+
| `parcels.neighbors(ref, country=)` | `GET /v1/parcels/{ref}/neighbors` | Spain, and countries where we hold a copy; `supported: false` (free) elsewhere |
|
|
76
82
|
| `parcels.at_point(lat, lng, country=)` | `GET /v1/search/coordinates` | All, including HR, SE and UK (Scotland) |
|
|
77
83
|
| `search_address_candidates(q, street=, number=, municipality=, postcode=, country=, limit=)` | `GET /v1/search/address/candidates` | Spain (with Basque Country and Navarre) and 26 more; not SE or HR |
|
|
78
84
|
| `parcels.find_by_address(text)` | `POST /v1/search/address/parse` | Spain, central Catastro, live (prefer the candidates search) |
|
|
@@ -81,17 +87,19 @@ with CatastroGPS() as client:
|
|
|
81
87
|
| `parcels.terrain(ref, country=, lat=, lng=)` | `GET /v1/parcels/{ref}/terrain` | All; `lat`/`lng` required outside ES, PV, NA, PT, FR, IT, DE |
|
|
82
88
|
| `parcels.ground_motion(ref, country=, lat=, lng=)` | `GET /v1/parcels/{ref}/ground-motion` | Same as terrain, inside EGMS coverage |
|
|
83
89
|
| `parcels.solar`, `parcels.agriculture`, `parcels.score` | `/solar`, `/agriculture`, `/score` | ES, PV, NA, PT, FR, IT, DE |
|
|
84
|
-
| `parcels.market(ref, country=)` | `/market` |
|
|
90
|
+
| `parcels.market(ref, country=)` | `/market` | Sales figures in FR, IT and DE (NRW); `zonePrices` (official province prices) in ES, PV, NA; PT `available: false` |
|
|
85
91
|
| `parcels.value_history(ref, country=)` | `/value-history` | ES, PV, NA, PT, FR, IT, DE, AT |
|
|
86
92
|
| `parcels.compare([(ref, country), ...])` | `POST /v1/parcels/compare` | 2 or 3 parcels in ES, PT, FR, IT, DE |
|
|
87
93
|
| `export.file(ref, "kml" \| "gpx", country=)` | `GET /v1/export/{format}` | Where a geometry exists |
|
|
88
94
|
| `resolve(text, hint=)` | `GET /v1/resolve` | Free, no quota: which country and kind a text is |
|
|
95
|
+
| `crop_catalog(lang=)` | `GET /v1/reference/crops` | Free, no quota: every `cropCode` with its name in the 10 languages |
|
|
96
|
+
| `locations.provinces()`, `locations.municipalities(region)`, `locations.streets(region, municipality, name=)` | `GET /v1/locations/...` | Spain, common territory |
|
|
89
97
|
|
|
90
98
|
## Examples
|
|
91
99
|
|
|
92
100
|
```python
|
|
93
101
|
in_warsaw = client.parcels.at_point(52.2297, 21.0122)
|
|
94
|
-
in_warsaw["
|
|
102
|
+
in_warsaw["reference"], in_warsaw.get("country")
|
|
95
103
|
|
|
96
104
|
found = client.search_address_candidates("Damrak 1, 1012 LG Amsterdam", country="NL")
|
|
97
105
|
found["candidates"][0]["reference"], found["candidates"][0]["confidence"]
|
|
@@ -110,8 +118,28 @@ kml_bytes = client.export.file("9872023VH5797S0001WX", "kml")
|
|
|
110
118
|
|
|
111
119
|
guess = client.resolve("05102200100005")
|
|
112
120
|
guess["candidates"]
|
|
121
|
+
|
|
122
|
+
crops = client.parcels.subparcels("46063A00100121", lang="en")
|
|
123
|
+
for row in crops["subparcels"]:
|
|
124
|
+
print(row["cropCode"], row.get("crop"), row.get("cropOriginal"), row["area"], row.get("useClass"))
|
|
125
|
+
|
|
126
|
+
sigpac = client.parcels.sigpac("46063A00100121", lang="en")
|
|
127
|
+
for enclosure in sigpac["enclosures"]:
|
|
128
|
+
print(enclosure["id"], enclosure["landUseCode"], enclosure.get("landUse"), enclosure["areaHa"], enclosure["irrigationPct"])
|
|
129
|
+
collection = client.parcels.sigpac_geojson("46063A00100121")
|
|
130
|
+
|
|
131
|
+
catalog = client.crop_catalog(lang="en")
|
|
132
|
+
names = {crop["code"]: crop["name"] for crop in catalog["crops"]}
|
|
133
|
+
|
|
134
|
+
around = client.parcels.neighbors("9872023VH5797S")
|
|
135
|
+
[n["reference"] for n in around["neighbors"]]
|
|
136
|
+
|
|
137
|
+
provinces = client.locations.provinces()["provinces"]
|
|
138
|
+
streets = client.locations.streets("CIUDAD REAL", "AGUDO", name="GLORIA")["streets"]
|
|
113
139
|
```
|
|
114
140
|
|
|
141
|
+
Crop names follow `lang=` (`es`, `ca`, `en`, `pt`, `fr`, `it`, `de`, `pl`, `nl`, `cs`; see `CROP_LANGUAGES`), then the `Accept-Language` header, then English; `cropOriginal` always keeps the label as the source writes it. The full rows with geometry come from `parcels.subparcels`; `parcels.get` only carries `subparcelCount` and a `cropSummary` (share of each crop). If the source does not answer, `subparcels` raises `ServiceUnavailableError` with code `SUB_001` and nothing is charged.
|
|
142
|
+
|
|
115
143
|
`terrain` and `ground_motion` carry a `source.attribution` string that must be shown next to the data. A ground motion answer with `status: "no_data"` and `reason: "no_reflectors"` means the satellite had nothing stable to measure (fields, forest, water): there is no figure, not a zero.
|
|
116
144
|
|
|
117
145
|
Responses are the `data` object of the English v1 API (`https://api.parcelgps.com/v1`) as a `dict`: `reference`, `municipality`, `parcelArea`, `latitude`, `longitude`… Values that come from an official source (land use, addresses) stay in its language. See the [API reference](https://www.parcelgps.com/en/api/docs) and the OpenAPI spec at `https://api.parcelgps.com/v1/openapi.json`. Version 2 of this SDK talks only to `/v1`; 1.x used the deprecated Spanish-named `/api` routes.
|
|
@@ -189,7 +217,7 @@ except QuotaExceededError as error:
|
|
|
189
217
|
| `NotFoundError` | `404 NOT_FOUND` |
|
|
190
218
|
| `QuotaExceededError` | `429 KEY_AUTH_004` |
|
|
191
219
|
| `RateLimitError` | `429 KEY_RATE_002`, `RATE_LIMIT_EXCEEDED`; `retry_after` |
|
|
192
|
-
| `ServiceUnavailableError` | `503 SERVICE_UNAVAILABLE
|
|
220
|
+
| `ServiceUnavailableError` | `503 SERVICE_UNAVAILABLE`, `SUB_001` / `SIG_001` (subparcels or SIGPAC source down, not charged); `retry_after` |
|
|
193
221
|
| `ServerError`, `TimeoutError`, `NetworkError` | `5xx`, client timeout, network failure |
|
|
194
222
|
|
|
195
223
|
Timeouts, network errors, per-minute 429s and 502/503/504 are retried up to `max_retries` times (default 2) with exponential backoff, waiting `Retry-After` when the API sends it (up to 60 s). An exhausted monthly quota is never retried.
|
|
@@ -5,7 +5,9 @@ Official Python client for the [Catastro GPS API](https://www.parcelgps.com/deve
|
|
|
5
5
|
- Look up a parcel by its **official cadastral reference** or by **coordinates**, with the country detected for you.
|
|
6
6
|
- Turn a **postal address into parcels** in Spain and 26 more countries, ranked by confidence.
|
|
7
7
|
- Import **every unit of a Spanish building** (dwellings, shops, garages) with paging and free `304` refreshes.
|
|
8
|
-
- Get the **parcel outline** (GeoJSON or a `[lat, lng]` ring),
|
|
8
|
+
- Get the **parcel outline** (GeoJSON or a `[lat, lng]` ring), **KML / GPX** exports and the **adjoining parcels**.
|
|
9
|
+
- **Crops and land use of each part of a parcel** (Spain with the foral territories, Austria, Estonia, Greece), with crop names in 10 languages and a free crop code catalogue.
|
|
10
|
+
- **Spanish provinces, municipalities and streets** to build a structured address search.
|
|
9
11
|
- **Relief, Natura 2000 and climate** (Copernicus DEM, EEA, ERA5-Land) and **ground motion** (Copernicus EGMS, mm/year) for any covered country.
|
|
10
12
|
- **Solar**, **agriculture**, **market**, **score**, **value history** and **comparison** for Spain, Portugal, France, Italy and Germany.
|
|
11
13
|
- Quota, prepaid balance and per-minute limit of every response, typed exceptions for every API code.
|
|
@@ -41,7 +43,11 @@ with CatastroGPS() as client:
|
|
|
41
43
|
|
|
42
44
|
| Method | Endpoint | Countries |
|
|
43
45
|
|--------|----------|-----------|
|
|
44
|
-
| `parcels.get(ref, country=)` | `GET /v1/parcels/{ref}` | All references (see coverage) |
|
|
46
|
+
| `parcels.get(ref, country=, lang=)` | `GET /v1/parcels/{ref}` | All references (see coverage). Carries `subparcelCount` and `cropSummary` |
|
|
47
|
+
| `parcels.subparcels(ref, country=, lang=)` | `GET /v1/parcels/{ref}/subparcels` | ES (with PV/NA), AT, DE, CZ, NL, FR, PT, SE, CH, FI, BE, IE, SI, EE, GR. 1 unit; 0 when the parcel has none |
|
|
48
|
+
| `parcels.sigpac(ref, country=, lang=)` | `GET /v1/parcels/{ref}/sigpac` | ES, PV, NA. SIGPAC enclosures with land use, irrigation, slope, CAP eligibility, incidents and outline. 1 unit; 0 when there are none; `SIG_001` is not charged |
|
|
49
|
+
| `parcels.sigpac_geojson(ref, country=, lang=)` | `GET /v1/parcels/{ref}/sigpac?format=geojson` | The same as a GeoJSON FeatureCollection (dict) |
|
|
50
|
+
| `parcels.neighbors(ref, country=)` | `GET /v1/parcels/{ref}/neighbors` | Spain, and countries where we hold a copy; `supported: false` (free) elsewhere |
|
|
45
51
|
| `parcels.at_point(lat, lng, country=)` | `GET /v1/search/coordinates` | All, including HR, SE and UK (Scotland) |
|
|
46
52
|
| `search_address_candidates(q, street=, number=, municipality=, postcode=, country=, limit=)` | `GET /v1/search/address/candidates` | Spain (with Basque Country and Navarre) and 26 more; not SE or HR |
|
|
47
53
|
| `parcels.find_by_address(text)` | `POST /v1/search/address/parse` | Spain, central Catastro, live (prefer the candidates search) |
|
|
@@ -50,17 +56,19 @@ with CatastroGPS() as client:
|
|
|
50
56
|
| `parcels.terrain(ref, country=, lat=, lng=)` | `GET /v1/parcels/{ref}/terrain` | All; `lat`/`lng` required outside ES, PV, NA, PT, FR, IT, DE |
|
|
51
57
|
| `parcels.ground_motion(ref, country=, lat=, lng=)` | `GET /v1/parcels/{ref}/ground-motion` | Same as terrain, inside EGMS coverage |
|
|
52
58
|
| `parcels.solar`, `parcels.agriculture`, `parcels.score` | `/solar`, `/agriculture`, `/score` | ES, PV, NA, PT, FR, IT, DE |
|
|
53
|
-
| `parcels.market(ref, country=)` | `/market` |
|
|
59
|
+
| `parcels.market(ref, country=)` | `/market` | Sales figures in FR, IT and DE (NRW); `zonePrices` (official province prices) in ES, PV, NA; PT `available: false` |
|
|
54
60
|
| `parcels.value_history(ref, country=)` | `/value-history` | ES, PV, NA, PT, FR, IT, DE, AT |
|
|
55
61
|
| `parcels.compare([(ref, country), ...])` | `POST /v1/parcels/compare` | 2 or 3 parcels in ES, PT, FR, IT, DE |
|
|
56
62
|
| `export.file(ref, "kml" \| "gpx", country=)` | `GET /v1/export/{format}` | Where a geometry exists |
|
|
57
63
|
| `resolve(text, hint=)` | `GET /v1/resolve` | Free, no quota: which country and kind a text is |
|
|
64
|
+
| `crop_catalog(lang=)` | `GET /v1/reference/crops` | Free, no quota: every `cropCode` with its name in the 10 languages |
|
|
65
|
+
| `locations.provinces()`, `locations.municipalities(region)`, `locations.streets(region, municipality, name=)` | `GET /v1/locations/...` | Spain, common territory |
|
|
58
66
|
|
|
59
67
|
## Examples
|
|
60
68
|
|
|
61
69
|
```python
|
|
62
70
|
in_warsaw = client.parcels.at_point(52.2297, 21.0122)
|
|
63
|
-
in_warsaw["
|
|
71
|
+
in_warsaw["reference"], in_warsaw.get("country")
|
|
64
72
|
|
|
65
73
|
found = client.search_address_candidates("Damrak 1, 1012 LG Amsterdam", country="NL")
|
|
66
74
|
found["candidates"][0]["reference"], found["candidates"][0]["confidence"]
|
|
@@ -79,8 +87,28 @@ kml_bytes = client.export.file("9872023VH5797S0001WX", "kml")
|
|
|
79
87
|
|
|
80
88
|
guess = client.resolve("05102200100005")
|
|
81
89
|
guess["candidates"]
|
|
90
|
+
|
|
91
|
+
crops = client.parcels.subparcels("46063A00100121", lang="en")
|
|
92
|
+
for row in crops["subparcels"]:
|
|
93
|
+
print(row["cropCode"], row.get("crop"), row.get("cropOriginal"), row["area"], row.get("useClass"))
|
|
94
|
+
|
|
95
|
+
sigpac = client.parcels.sigpac("46063A00100121", lang="en")
|
|
96
|
+
for enclosure in sigpac["enclosures"]:
|
|
97
|
+
print(enclosure["id"], enclosure["landUseCode"], enclosure.get("landUse"), enclosure["areaHa"], enclosure["irrigationPct"])
|
|
98
|
+
collection = client.parcels.sigpac_geojson("46063A00100121")
|
|
99
|
+
|
|
100
|
+
catalog = client.crop_catalog(lang="en")
|
|
101
|
+
names = {crop["code"]: crop["name"] for crop in catalog["crops"]}
|
|
102
|
+
|
|
103
|
+
around = client.parcels.neighbors("9872023VH5797S")
|
|
104
|
+
[n["reference"] for n in around["neighbors"]]
|
|
105
|
+
|
|
106
|
+
provinces = client.locations.provinces()["provinces"]
|
|
107
|
+
streets = client.locations.streets("CIUDAD REAL", "AGUDO", name="GLORIA")["streets"]
|
|
82
108
|
```
|
|
83
109
|
|
|
110
|
+
Crop names follow `lang=` (`es`, `ca`, `en`, `pt`, `fr`, `it`, `de`, `pl`, `nl`, `cs`; see `CROP_LANGUAGES`), then the `Accept-Language` header, then English; `cropOriginal` always keeps the label as the source writes it. The full rows with geometry come from `parcels.subparcels`; `parcels.get` only carries `subparcelCount` and a `cropSummary` (share of each crop). If the source does not answer, `subparcels` raises `ServiceUnavailableError` with code `SUB_001` and nothing is charged.
|
|
111
|
+
|
|
84
112
|
`terrain` and `ground_motion` carry a `source.attribution` string that must be shown next to the data. A ground motion answer with `status: "no_data"` and `reason: "no_reflectors"` means the satellite had nothing stable to measure (fields, forest, water): there is no figure, not a zero.
|
|
85
113
|
|
|
86
114
|
Responses are the `data` object of the English v1 API (`https://api.parcelgps.com/v1`) as a `dict`: `reference`, `municipality`, `parcelArea`, `latitude`, `longitude`… Values that come from an official source (land use, addresses) stay in its language. See the [API reference](https://www.parcelgps.com/en/api/docs) and the OpenAPI spec at `https://api.parcelgps.com/v1/openapi.json`. Version 2 of this SDK talks only to `/v1`; 1.x used the deprecated Spanish-named `/api` routes.
|
|
@@ -158,7 +186,7 @@ except QuotaExceededError as error:
|
|
|
158
186
|
| `NotFoundError` | `404 NOT_FOUND` |
|
|
159
187
|
| `QuotaExceededError` | `429 KEY_AUTH_004` |
|
|
160
188
|
| `RateLimitError` | `429 KEY_RATE_002`, `RATE_LIMIT_EXCEEDED`; `retry_after` |
|
|
161
|
-
| `ServiceUnavailableError` | `503 SERVICE_UNAVAILABLE
|
|
189
|
+
| `ServiceUnavailableError` | `503 SERVICE_UNAVAILABLE`, `SUB_001` / `SIG_001` (subparcels or SIGPAC source down, not charged); `retry_after` |
|
|
162
190
|
| `ServerError`, `TimeoutError`, `NetworkError` | `5xx`, client timeout, network failure |
|
|
163
191
|
|
|
164
192
|
Timeouts, network errors, per-minute 429s and 502/503/504 are retried up to `max_retries` times (default 2) with exponential backoff, waiting `Retry-After` when the API sends it (up to 60 s). An exhausted monthly quota is never retried.
|
|
@@ -20,6 +20,7 @@ from catastrogps.export import EXPORT_FORMATS
|
|
|
20
20
|
from catastrogps.parcels import (
|
|
21
21
|
ADDRESS_COUNTRY_CODES,
|
|
22
22
|
COUNTRY_CODES,
|
|
23
|
+
CROP_LANGUAGES,
|
|
23
24
|
ENRICHMENT_COUNTRY_CODES,
|
|
24
25
|
UNITS_COUNTRY_CODES,
|
|
25
26
|
)
|
|
@@ -27,6 +28,7 @@ from catastrogps.parcels import (
|
|
|
27
28
|
__all__ = [
|
|
28
29
|
"ADDRESS_COUNTRY_CODES",
|
|
29
30
|
"COUNTRY_CODES",
|
|
31
|
+
"CROP_LANGUAGES",
|
|
30
32
|
"DEFAULT_BASE_URL",
|
|
31
33
|
"ENRICHMENT_COUNTRY_CODES",
|
|
32
34
|
"EXPORT_FORMATS",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "2.2.0"
|
|
@@ -20,7 +20,8 @@ from catastrogps.errors import (
|
|
|
20
20
|
)
|
|
21
21
|
from catastrogps.export import ExportResource
|
|
22
22
|
from catastrogps.fincas import FincasResource
|
|
23
|
-
from catastrogps.
|
|
23
|
+
from catastrogps.locations import LocationsResource
|
|
24
|
+
from catastrogps.parcels import ParcelsResource, crop_language
|
|
24
25
|
|
|
25
26
|
DEFAULT_BASE_URL = "https://api.parcelgps.com"
|
|
26
27
|
DEFAULT_TIMEOUT = 30.0
|
|
@@ -61,6 +62,7 @@ class CatastroGPS:
|
|
|
61
62
|
self.parcels = ParcelsResource(self)
|
|
62
63
|
self.export = ExportResource(self)
|
|
63
64
|
self.fincas = FincasResource(self)
|
|
65
|
+
self.locations = LocationsResource(self)
|
|
64
66
|
|
|
65
67
|
def search_address_candidates(
|
|
66
68
|
self,
|
|
@@ -96,6 +98,9 @@ class CatastroGPS:
|
|
|
96
98
|
def resolve(self, text: str, *, hint: str | None = None) -> dict[str, Any]:
|
|
97
99
|
return self.request("GET", "/v1/resolve", query={"q": text, "hint": hint})
|
|
98
100
|
|
|
101
|
+
def crop_catalog(self, *, lang: str | None = None) -> dict[str, Any]:
|
|
102
|
+
return self.request("GET", "/v1/reference/crops", query={"lang": crop_language(lang)})
|
|
103
|
+
|
|
99
104
|
def request(
|
|
100
105
|
self,
|
|
101
106
|
method: str,
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any
|
|
4
|
+
|
|
5
|
+
from catastrogps.errors import CatastroGPSError
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from catastrogps.client import CatastroGPS
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class LocationsResource:
|
|
12
|
+
def __init__(self, client: CatastroGPS) -> None:
|
|
13
|
+
self._client = client
|
|
14
|
+
|
|
15
|
+
def provinces(self) -> dict[str, Any]:
|
|
16
|
+
return self._client.request("GET", "/v1/locations/provinces")
|
|
17
|
+
|
|
18
|
+
def municipalities(self, region: str) -> dict[str, Any]:
|
|
19
|
+
return self._client.request(
|
|
20
|
+
"GET", "/v1/locations/municipalities", query={"region": _required("region", region)}
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
def streets(self, region: str, municipality: str, *, name: str | None = None) -> dict[str, Any]:
|
|
24
|
+
return self._client.request(
|
|
25
|
+
"GET",
|
|
26
|
+
"/v1/locations/streets",
|
|
27
|
+
query={
|
|
28
|
+
"region": _required("region", region),
|
|
29
|
+
"municipality": _required("municipality", municipality),
|
|
30
|
+
"name": (name or "").strip() or None,
|
|
31
|
+
},
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _required(field: str, value: str) -> str:
|
|
36
|
+
cleaned = (value or "").strip()
|
|
37
|
+
if not cleaned:
|
|
38
|
+
raise CatastroGPSError(f"{field} must not be empty")
|
|
39
|
+
return cleaned
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import json
|
|
3
4
|
import math
|
|
4
5
|
from typing import TYPE_CHECKING, Any
|
|
5
6
|
from urllib.parse import quote
|
|
@@ -77,6 +78,8 @@ ADDRESS_COUNTRY_CODES = (
|
|
|
77
78
|
|
|
78
79
|
UNITS_COUNTRY_CODES = ("ES", "PV", "NA")
|
|
79
80
|
|
|
81
|
+
CROP_LANGUAGES = ("es", "ca", "en", "pt", "fr", "it", "de", "pl", "nl", "cs")
|
|
82
|
+
|
|
80
83
|
MIN_COMPARE = 2
|
|
81
84
|
MAX_COMPARE = 3
|
|
82
85
|
|
|
@@ -92,8 +95,35 @@ class ParcelsResource:
|
|
|
92
95
|
def __init__(self, client: CatastroGPS) -> None:
|
|
93
96
|
self._client = client
|
|
94
97
|
|
|
95
|
-
def get(self, reference: str, *, country: str | None = None) -> dict[str, Any]:
|
|
96
|
-
return self._client.request(
|
|
98
|
+
def get(self, reference: str, *, country: str | None = None, lang: str | None = None) -> dict[str, Any]:
|
|
99
|
+
return self._client.request(
|
|
100
|
+
"GET", parcel_path(reference), query={"country": country, "lang": crop_language(lang)}
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def subparcels(self, reference: str, *, country: str | None = None, lang: str | None = None) -> dict[str, Any]:
|
|
104
|
+
return self._client.request(
|
|
105
|
+
"GET", parcel_path(reference, "/subparcels"), query={"country": country, "lang": crop_language(lang)}
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
def sigpac(self, reference: str, *, country: str | None = None, lang: str | None = None) -> dict[str, Any]:
|
|
109
|
+
return self._client.request(
|
|
110
|
+
"GET", parcel_path(reference, "/sigpac"), query={"country": country, "lang": crop_language(lang)}
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def sigpac_geojson(self, reference: str, *, country: str | None = None, lang: str | None = None) -> dict[str, Any]:
|
|
114
|
+
content = self._client.request(
|
|
115
|
+
"GET",
|
|
116
|
+
parcel_path(reference, "/sigpac"),
|
|
117
|
+
query={"country": country, "lang": crop_language(lang), "format": "geojson"},
|
|
118
|
+
raw=True,
|
|
119
|
+
)
|
|
120
|
+
try:
|
|
121
|
+
return json.loads(content)
|
|
122
|
+
except ValueError as error:
|
|
123
|
+
raise CatastroGPSError("SIGPAC GeoJSON response is not valid JSON") from error
|
|
124
|
+
|
|
125
|
+
def neighbors(self, reference: str, *, country: str | None = None) -> dict[str, Any]:
|
|
126
|
+
return self._client.request("GET", parcel_path(reference, "/neighbors"), query={"country": country})
|
|
97
127
|
|
|
98
128
|
def at_point(self, lat: float, lng: float, *, country: str | None = None) -> dict[str, Any]:
|
|
99
129
|
if not (_finite(lat) and _finite(lng)):
|
|
@@ -144,6 +174,15 @@ class ParcelsResource:
|
|
|
144
174
|
return self._client.request("POST", "/v1/parcels/compare", body={"parcels": items})
|
|
145
175
|
|
|
146
176
|
|
|
177
|
+
def crop_language(lang: str | None) -> str | None:
|
|
178
|
+
if lang is None:
|
|
179
|
+
return None
|
|
180
|
+
cleaned = lang.strip().lower()
|
|
181
|
+
if cleaned not in CROP_LANGUAGES:
|
|
182
|
+
raise CatastroGPSError(f"lang must be one of {', '.join(CROP_LANGUAGES)}")
|
|
183
|
+
return cleaned
|
|
184
|
+
|
|
185
|
+
|
|
147
186
|
def _compare_item(parcel: tuple[str, str] | dict[str, str]) -> dict[str, str]:
|
|
148
187
|
if isinstance(parcel, dict):
|
|
149
188
|
reference, country = parcel.get("reference", ""), parcel.get("country", "")
|
|
@@ -51,7 +51,7 @@ dev = [
|
|
|
51
51
|
path = "catastrogps/_version.py"
|
|
52
52
|
|
|
53
53
|
[tool.hatch.build.targets.sdist]
|
|
54
|
-
include = ["catastrogps", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
54
|
+
include = ["catastrogps", "tests", "README.md", "CHANGELOG.md", "LICENSE", "pyproject.toml"]
|
|
55
55
|
|
|
56
56
|
[tool.hatch.build.targets.wheel]
|
|
57
57
|
packages = ["catastrogps"]
|
|
@@ -229,6 +229,13 @@ def test_every_call_uses_the_v1_api():
|
|
|
229
229
|
client.parcels.value_history("R")
|
|
230
230
|
client.parcels.compare([("A", "ES"), ("B", "ES")])
|
|
231
231
|
client.resolve("R")
|
|
232
|
+
client.parcels.subparcels("R")
|
|
233
|
+
client.parcels.neighbors("R")
|
|
234
|
+
client.locations.provinces()
|
|
235
|
+
client.locations.municipalities("CIUDAD REAL")
|
|
236
|
+
client.locations.streets("CIUDAD REAL", "AGUDO")
|
|
237
|
+
client.crop_catalog()
|
|
238
|
+
assert len(seen) == 19
|
|
232
239
|
assert all(url.host == "api.parcelgps.com" for url in seen)
|
|
233
240
|
assert all(url.path.startswith("/v1/") for url in seen)
|
|
234
241
|
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
import catastrogps.client as client_module
|
|
7
|
+
from catastrogps import (
|
|
8
|
+
AuthenticationError,
|
|
9
|
+
CatastroGPS,
|
|
10
|
+
CatastroGPSError,
|
|
11
|
+
CoverageError,
|
|
12
|
+
NotFoundError,
|
|
13
|
+
QuotaExceededError,
|
|
14
|
+
RateLimitError,
|
|
15
|
+
ServerError,
|
|
16
|
+
ServiceUnavailableError,
|
|
17
|
+
TimeoutError,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Recorder:
|
|
22
|
+
def __init__(self, *responses):
|
|
23
|
+
self.responses = list(responses)
|
|
24
|
+
self.requests = []
|
|
25
|
+
|
|
26
|
+
def __call__(self, request: httpx.Request) -> httpx.Response:
|
|
27
|
+
self.requests.append(request)
|
|
28
|
+
response = self.responses.pop(0)
|
|
29
|
+
if isinstance(response, Exception):
|
|
30
|
+
raise response
|
|
31
|
+
return response
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def last(self) -> httpx.Request:
|
|
35
|
+
return self.requests[-1]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@pytest.fixture(autouse=True)
|
|
39
|
+
def no_sleep(monkeypatch):
|
|
40
|
+
monkeypatch.setattr(client_module.time, "sleep", lambda _seconds: None)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def make(*responses, max_retries=0):
|
|
44
|
+
recorder = Recorder(*responses)
|
|
45
|
+
http = httpx.Client(transport=httpx.MockTransport(recorder))
|
|
46
|
+
client = CatastroGPS(
|
|
47
|
+
"pk_test_000000000000", base_url="https://api.example.test", http_client=http, max_retries=max_retries
|
|
48
|
+
)
|
|
49
|
+
return client, recorder
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def ok(data, headers=None):
|
|
53
|
+
return httpx.Response(200, json={"success": True, "data": data}, headers=headers)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def fail(status, code, message="error", headers=None, details=None):
|
|
57
|
+
body = {"success": False, "code": code, "message": message}
|
|
58
|
+
if details is not None:
|
|
59
|
+
body["details"] = details
|
|
60
|
+
return httpx.Response(status, json=body, headers=headers)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
SIGPAC = {
|
|
64
|
+
"reference": "46063A00100121",
|
|
65
|
+
"country": "ES",
|
|
66
|
+
"sigpacParcel": {"province": 46, "municipality": 63, "aggregate": 0, "zone": 0, "polygon": 1, "parcel": 121},
|
|
67
|
+
"match": "reference",
|
|
68
|
+
"count": 2,
|
|
69
|
+
"totalAreaHa": 0.8815,
|
|
70
|
+
"crs": "EPSG:4258 (ETRS89, lon/lat; equal to WGS84 within about 1 m)",
|
|
71
|
+
"retrievedAt": "2026-10-22T13:47:26Z",
|
|
72
|
+
"source": {"name": "SIGPAC", "provider": "FEGA", "license": "Ley 37/2007", "attribution": "Fuente: FEGA — SIGPAC"},
|
|
73
|
+
"enclosures": [
|
|
74
|
+
{
|
|
75
|
+
"id": "46:63:0:0:1:121:2",
|
|
76
|
+
"enclosure": 2,
|
|
77
|
+
"landUseCode": "FY",
|
|
78
|
+
"landUse": "Fruit trees",
|
|
79
|
+
"cropCode": "SIGPAC:FY",
|
|
80
|
+
"useClass": "orchard",
|
|
81
|
+
"areaHa": 0.0513,
|
|
82
|
+
"irrigationPct": 0,
|
|
83
|
+
"meanSlopePct": 7.6,
|
|
84
|
+
"altitudeM": 117,
|
|
85
|
+
"pastureEligibilityPct": None,
|
|
86
|
+
"capRegion": 12,
|
|
87
|
+
"incidents": [{"code": 199, "description": "Recinto inactivo"}],
|
|
88
|
+
"geometry": {"type": "Polygon", "coordinates": []},
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
"id": "46:63:0:0:1:121:9",
|
|
92
|
+
"enclosure": 9,
|
|
93
|
+
"landUseCode": "ZZ",
|
|
94
|
+
"areaHa": 0.0039,
|
|
95
|
+
"irrigationPct": None,
|
|
96
|
+
"meanSlopePct": None,
|
|
97
|
+
"altitudeM": None,
|
|
98
|
+
"pastureEligibilityPct": None,
|
|
99
|
+
"capRegion": None,
|
|
100
|
+
"incidents": [],
|
|
101
|
+
"geometry": None,
|
|
102
|
+
},
|
|
103
|
+
],
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
GEOJSON = {
|
|
107
|
+
"type": "FeatureCollection",
|
|
108
|
+
"reference": "46063A00100121",
|
|
109
|
+
"count": 1,
|
|
110
|
+
"features": [{"type": "Feature", "properties": {"landUseCode": "FY"}, "geometry": None}],
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_sigpac_sends_country_and_lang_and_returns_data():
|
|
115
|
+
client, rec = make(ok(SIGPAC, headers={"X-Quota-Remaining": "41"}))
|
|
116
|
+
out = client.parcels.sigpac(" 46063A00100121 ", country="ES", lang="EN")
|
|
117
|
+
assert rec.last.method == "GET"
|
|
118
|
+
assert rec.last.url.path == "/v1/parcels/46063A00100121/sigpac"
|
|
119
|
+
assert dict(rec.last.url.params) == {"country": "ES", "lang": "en"}
|
|
120
|
+
assert rec.last.headers["Accept"] == "application/json"
|
|
121
|
+
assert out["count"] == 2
|
|
122
|
+
assert out["sigpacParcel"]["parcel"] == 121
|
|
123
|
+
assert out["enclosures"][0]["incidents"][0]["code"] == 199
|
|
124
|
+
assert out["enclosures"][1]["irrigationPct"] is None
|
|
125
|
+
assert out["enclosures"][1]["geometry"] is None
|
|
126
|
+
assert client.last_quota["remaining"] == 41
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_sigpac_without_options_sends_no_query():
|
|
130
|
+
client, rec = make(ok(SIGPAC))
|
|
131
|
+
client.parcels.sigpac("46063A00100121")
|
|
132
|
+
assert dict(rec.last.url.params) == {}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def test_sigpac_no_enclosures():
|
|
136
|
+
empty = {**SIGPAC, "sigpacParcel": None, "match": "point", "count": 0, "totalAreaHa": 0, "enclosures": []}
|
|
137
|
+
client, _ = make(ok(empty))
|
|
138
|
+
out = client.parcels.sigpac("9872023VH5797S0001WX")
|
|
139
|
+
assert out["sigpacParcel"] is None
|
|
140
|
+
assert out["enclosures"] == []
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@pytest.mark.parametrize("call", ["sigpac", "sigpac_geojson"])
|
|
144
|
+
def test_sigpac_validates_before_request(call):
|
|
145
|
+
client, rec = make()
|
|
146
|
+
with pytest.raises(CatastroGPSError):
|
|
147
|
+
getattr(client.parcels, call)(" ")
|
|
148
|
+
with pytest.raises(CatastroGPSError):
|
|
149
|
+
getattr(client.parcels, call)("46063A00100121", lang="ja")
|
|
150
|
+
assert rec.requests == []
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_sigpac_geojson_parses_feature_collection():
|
|
154
|
+
response = httpx.Response(
|
|
155
|
+
200,
|
|
156
|
+
content=json.dumps(GEOJSON).encode(),
|
|
157
|
+
headers={
|
|
158
|
+
"Content-Type": "application/geo+json",
|
|
159
|
+
"Content-Disposition": 'attachment; filename="sigpac.geojson"',
|
|
160
|
+
"X-Quota-Remaining": "40",
|
|
161
|
+
},
|
|
162
|
+
)
|
|
163
|
+
client, rec = make(response)
|
|
164
|
+
out = client.parcels.sigpac_geojson("46063A00100121", country="NA", lang="de")
|
|
165
|
+
assert dict(rec.last.url.params) == {"country": "NA", "lang": "de", "format": "geojson"}
|
|
166
|
+
assert rec.last.headers["Accept"] == "*/*"
|
|
167
|
+
assert out == GEOJSON
|
|
168
|
+
assert client.last_quota["remaining"] == 40
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def test_sigpac_geojson_invalid_body():
|
|
172
|
+
client, _ = make(httpx.Response(200, content=b"<html>", headers={"Content-Type": "text/html"}))
|
|
173
|
+
with pytest.raises(CatastroGPSError, match="not valid JSON"):
|
|
174
|
+
client.parcels.sigpac_geojson("46063A00100121")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@pytest.mark.parametrize(
|
|
178
|
+
"status,code,error",
|
|
179
|
+
[
|
|
180
|
+
(401, "KEY_AUTH_002", AuthenticationError),
|
|
181
|
+
(404, "NOT_FOUND", NotFoundError),
|
|
182
|
+
(422, "CNV_COVERAGE", CoverageError),
|
|
183
|
+
(429, "KEY_AUTH_004", QuotaExceededError),
|
|
184
|
+
(429, "KEY_RATE_002", RateLimitError),
|
|
185
|
+
(500, "INTERNAL", ServerError),
|
|
186
|
+
(503, "SIG_001", ServiceUnavailableError),
|
|
187
|
+
],
|
|
188
|
+
)
|
|
189
|
+
@pytest.mark.parametrize("call", ["sigpac", "sigpac_geojson"])
|
|
190
|
+
def test_sigpac_errors(call, status, code, error):
|
|
191
|
+
details = {"feature": "sigpac", "supportedCountries": ["ES", "PV", "NA"]}
|
|
192
|
+
client, rec = make(fail(status, code, details=details, headers={"Retry-After": "3"}))
|
|
193
|
+
with pytest.raises(error) as caught:
|
|
194
|
+
getattr(client.parcels, call)("CH119192997709")
|
|
195
|
+
assert caught.value.code == code
|
|
196
|
+
assert caught.value.status == status
|
|
197
|
+
assert len(rec.requests) == 1
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def test_sigpac_down_is_retried_then_succeeds():
|
|
201
|
+
client, rec = make(
|
|
202
|
+
fail(503, "SIG_001", "The SIGPAC enclosures could not be read right now.", headers={"Retry-After": "2"}),
|
|
203
|
+
ok(SIGPAC),
|
|
204
|
+
max_retries=1,
|
|
205
|
+
)
|
|
206
|
+
assert client.parcels.sigpac("46063A00100121")["count"] == 2
|
|
207
|
+
assert len(rec.requests) == 2
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def test_sigpac_quota_exceeded_not_retried():
|
|
211
|
+
client, rec = make(fail(429, "KEY_AUTH_004"), max_retries=3)
|
|
212
|
+
with pytest.raises(QuotaExceededError):
|
|
213
|
+
client.parcels.sigpac("46063A00100121")
|
|
214
|
+
assert len(rec.requests) == 1
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def test_sigpac_timeout():
|
|
218
|
+
client, rec = make(httpx.ReadTimeout("slow"), httpx.ReadTimeout("slow"), max_retries=1)
|
|
219
|
+
with pytest.raises(TimeoutError):
|
|
220
|
+
client.parcels.sigpac("46063A00100121")
|
|
221
|
+
assert len(rec.requests) == 2
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import httpx
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
import catastrogps.client as client_module
|
|
5
|
+
from catastrogps import (
|
|
6
|
+
CROP_LANGUAGES,
|
|
7
|
+
AuthenticationError,
|
|
8
|
+
CatastroGPS,
|
|
9
|
+
CatastroGPSError,
|
|
10
|
+
NotFoundError,
|
|
11
|
+
QuotaExceededError,
|
|
12
|
+
RateLimitError,
|
|
13
|
+
ServiceUnavailableError,
|
|
14
|
+
ValidationError,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Recorder:
|
|
19
|
+
def __init__(self, *responses):
|
|
20
|
+
self.responses = list(responses)
|
|
21
|
+
self.requests = []
|
|
22
|
+
|
|
23
|
+
def __call__(self, request: httpx.Request) -> httpx.Response:
|
|
24
|
+
self.requests.append(request)
|
|
25
|
+
return self.responses.pop(0)
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def last(self) -> httpx.Request:
|
|
29
|
+
return self.requests[-1]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.fixture(autouse=True)
|
|
33
|
+
def no_sleep(monkeypatch):
|
|
34
|
+
monkeypatch.setattr(client_module.time, "sleep", lambda _seconds: None)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def make(*responses, max_retries=0):
|
|
38
|
+
recorder = Recorder(*responses)
|
|
39
|
+
http = httpx.Client(transport=httpx.MockTransport(recorder))
|
|
40
|
+
client = CatastroGPS(
|
|
41
|
+
"pk_test_000000000000", base_url="https://api.example.test", http_client=http, max_retries=max_retries
|
|
42
|
+
)
|
|
43
|
+
return client, recorder
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def ok(data, headers=None):
|
|
47
|
+
return httpx.Response(200, json={"success": True, "data": data}, headers=headers)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def fail(status, code, message="error", headers=None, details=None):
|
|
51
|
+
body = {"success": False, "code": code, "message": message}
|
|
52
|
+
if details is not None:
|
|
53
|
+
body["details"] = details
|
|
54
|
+
return httpx.Response(status, json=body, headers=headers)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
SUBPARCELS = {
|
|
58
|
+
"reference": "46063A00100121",
|
|
59
|
+
"country": "ES",
|
|
60
|
+
"parcelArea": 8814,
|
|
61
|
+
"count": 2,
|
|
62
|
+
"subparcels": [
|
|
63
|
+
{
|
|
64
|
+
"id": "a",
|
|
65
|
+
"cropCode": "G-",
|
|
66
|
+
"crop": "Algarrobo de secano",
|
|
67
|
+
"cropOriginal": "Algarrobo secano",
|
|
68
|
+
"intensity": 1,
|
|
69
|
+
"area": 6623,
|
|
70
|
+
"kind": "cadastral",
|
|
71
|
+
"useClass": "orchard",
|
|
72
|
+
"source": "Catastro",
|
|
73
|
+
"geometry": {"type": "MultiPolygon", "coordinates": []},
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
"id": "b",
|
|
77
|
+
"cropCode": "E-",
|
|
78
|
+
"crop": "Pastos",
|
|
79
|
+
"cropOriginal": "Pastos",
|
|
80
|
+
"area": 2191,
|
|
81
|
+
"kind": "cadastral",
|
|
82
|
+
"landType": "rustic",
|
|
83
|
+
"landClass": "R",
|
|
84
|
+
"useClass": "grassland",
|
|
85
|
+
"useClassName": "Pastos",
|
|
86
|
+
},
|
|
87
|
+
],
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_subparcels_send_country_and_lang_and_return_the_crop_codes():
|
|
92
|
+
client, rec = make(ok(SUBPARCELS, headers={"X-Quota-Remaining": "41"}))
|
|
93
|
+
data = client.parcels.subparcels("46063A00100121", country="ES", lang="ES")
|
|
94
|
+
assert rec.last.url.path == "/v1/parcels/46063A00100121/subparcels"
|
|
95
|
+
assert rec.last.url.params["country"] == "ES"
|
|
96
|
+
assert rec.last.url.params["lang"] == "es"
|
|
97
|
+
assert data["count"] == 2
|
|
98
|
+
assert [s["cropCode"] for s in data["subparcels"]] == ["G-", "E-"]
|
|
99
|
+
assert data["subparcels"][0]["cropOriginal"] == "Algarrobo secano"
|
|
100
|
+
assert "landGrade" not in data["subparcels"][0]
|
|
101
|
+
assert client.last_quota["remaining"] == 41
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_subparcels_without_options_send_no_query():
|
|
105
|
+
client, rec = make(ok({"reference": "R", "count": 0, "subparcels": []}))
|
|
106
|
+
data = client.parcels.subparcels("R")
|
|
107
|
+
assert data["subparcels"] == []
|
|
108
|
+
assert dict(rec.last.url.params) == {}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_subparcels_source_failure_is_a_service_unavailable_with_retry_after():
|
|
112
|
+
client, _ = make(fail(503, "SUB_001", "Subparcels could not be read", headers={"Retry-After": "5"}))
|
|
113
|
+
with pytest.raises(ServiceUnavailableError) as info:
|
|
114
|
+
client.parcels.subparcels("46063A00100121")
|
|
115
|
+
assert info.value.status == 503
|
|
116
|
+
assert info.value.code == "SUB_001"
|
|
117
|
+
assert info.value.retry_after == 5
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_subparcels_source_failure_is_retried_then_answers():
|
|
121
|
+
client, rec = make(fail(503, "SUB_001", headers={"Retry-After": "1"}), ok(SUBPARCELS), max_retries=1)
|
|
122
|
+
assert client.parcels.subparcels("46063A00100121")["count"] == 2
|
|
123
|
+
assert len(rec.requests) == 2
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_subparcels_reject_an_unknown_language_before_calling():
|
|
127
|
+
client, rec = make()
|
|
128
|
+
with pytest.raises(CatastroGPSError, match="lang must be one of"):
|
|
129
|
+
client.parcels.subparcels("R", lang="xx")
|
|
130
|
+
assert rec.requests == []
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_subparcels_need_a_reference():
|
|
134
|
+
client, rec = make()
|
|
135
|
+
with pytest.raises(CatastroGPSError, match="reference must not be empty"):
|
|
136
|
+
client.parcels.subparcels(" ")
|
|
137
|
+
assert rec.requests == []
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def test_parcel_takes_lang_and_carries_the_crop_summary():
|
|
141
|
+
parcel = {
|
|
142
|
+
"reference": "46063A00100121",
|
|
143
|
+
"subparcelCount": 3,
|
|
144
|
+
"cropSummary": [{"cropCode": "G-", "crop": "Rainfed carob", "area": 6623, "share": 0.75}],
|
|
145
|
+
}
|
|
146
|
+
client, rec = make(ok(parcel))
|
|
147
|
+
data = client.parcels.get("46063A00100121", lang="en")
|
|
148
|
+
assert rec.last.url.params["lang"] == "en"
|
|
149
|
+
assert data["subparcelCount"] == 3
|
|
150
|
+
assert data["cropSummary"][0]["share"] == 0.75
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_neighbors_list_references_and_centres():
|
|
154
|
+
neighbors = {
|
|
155
|
+
"country": "ES",
|
|
156
|
+
"supported": True,
|
|
157
|
+
"count": 1,
|
|
158
|
+
"neighbors": [{"reference": "9871005VH5797S", "latitude": 38.64, "longitude": -3.46}],
|
|
159
|
+
}
|
|
160
|
+
client, rec = make(ok(neighbors))
|
|
161
|
+
data = client.parcels.neighbors("9872023VH5797S", country="ES")
|
|
162
|
+
assert rec.last.url.path == "/v1/parcels/9872023VH5797S/neighbors"
|
|
163
|
+
assert rec.last.url.params["country"] == "ES"
|
|
164
|
+
assert data["neighbors"][0]["reference"] == "9871005VH5797S"
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def test_neighbors_unsupported_country_is_an_empty_answer():
|
|
168
|
+
client, _ = make(ok({"country": "SE", "supported": False, "count": 0, "neighbors": []}))
|
|
169
|
+
data = client.parcels.neighbors("R", country="SE")
|
|
170
|
+
assert data["supported"] is False
|
|
171
|
+
assert data["neighbors"] == []
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def test_neighbors_of_an_unknown_parcel_raise_not_found():
|
|
175
|
+
client, _ = make(fail(404, "NOT_FOUND", "No parcel was found"))
|
|
176
|
+
with pytest.raises(NotFoundError):
|
|
177
|
+
client.parcels.neighbors("R")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def test_provinces():
|
|
181
|
+
client, rec = make(ok({"total": 1, "provinces": [{"code": "13", "name": "CIUDAD REAL"}]}))
|
|
182
|
+
data = client.locations.provinces()
|
|
183
|
+
assert rec.last.url.path == "/v1/locations/provinces"
|
|
184
|
+
assert data["provinces"][0]["name"] == "CIUDAD REAL"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def test_municipalities_send_the_region():
|
|
188
|
+
client, rec = make(ok({"total": 1, "municipalities": [{"code": "2", "ineCode": "002", "name": "AGUDO"}]}))
|
|
189
|
+
data = client.locations.municipalities(" CIUDAD REAL ")
|
|
190
|
+
assert rec.last.url.path == "/v1/locations/municipalities"
|
|
191
|
+
assert rec.last.url.params["region"] == "CIUDAD REAL"
|
|
192
|
+
assert data["municipalities"][0]["ineCode"] == "002"
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def test_streets_send_region_municipality_and_name():
|
|
196
|
+
streets = {"total": 1, "streets": [{"code": "33", "type": "CL", "name": "GLORIA", "fullName": "CL GLORIA"}]}
|
|
197
|
+
client, rec = make(ok(streets))
|
|
198
|
+
data = client.locations.streets("CIUDAD REAL", "AGUDO", name="glo")
|
|
199
|
+
assert rec.last.url.path == "/v1/locations/streets"
|
|
200
|
+
assert dict(rec.last.url.params) == {"region": "CIUDAD REAL", "municipality": "AGUDO", "name": "glo"}
|
|
201
|
+
assert data["streets"][0]["fullName"] == "CL GLORIA"
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def test_streets_without_name_filter():
|
|
205
|
+
client, rec = make(ok({"total": 0, "streets": []}))
|
|
206
|
+
client.locations.streets("CIUDAD REAL", "AGUDO", name=" ")
|
|
207
|
+
assert "name" not in rec.last.url.params
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@pytest.mark.parametrize(
|
|
211
|
+
("call", "message"),
|
|
212
|
+
[
|
|
213
|
+
(lambda c: c.locations.municipalities(""), "region must not be empty"),
|
|
214
|
+
(lambda c: c.locations.streets("", "AGUDO"), "region must not be empty"),
|
|
215
|
+
(lambda c: c.locations.streets("CIUDAD REAL", " "), "municipality must not be empty"),
|
|
216
|
+
],
|
|
217
|
+
)
|
|
218
|
+
def test_locations_validate_before_calling(call, message):
|
|
219
|
+
client, rec = make()
|
|
220
|
+
with pytest.raises(CatastroGPSError, match=message):
|
|
221
|
+
call(client)
|
|
222
|
+
assert rec.requests == []
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def test_locations_validation_error_from_the_api():
|
|
226
|
+
client, _ = make(fail(400, "VALIDATION_ERROR", "The 'region' parameter is required."))
|
|
227
|
+
with pytest.raises(ValidationError):
|
|
228
|
+
client.locations.municipalities("NOWHERE")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def test_crop_catalog_sends_lang_and_returns_the_codes():
|
|
232
|
+
catalog = {
|
|
233
|
+
"locale": "de",
|
|
234
|
+
"locales": list(CROP_LANGUAGES),
|
|
235
|
+
"sources": ["ES", "AT"],
|
|
236
|
+
"count": 1,
|
|
237
|
+
"useClasses": [{"code": "vineyard", "name": "Weinbau", "labels": {"en": "Vineyard"}}],
|
|
238
|
+
"crops": [{"code": "AT:53", "source": "AT", "name": "Weingärten", "original": "Weingärten",
|
|
239
|
+
"useClass": "vineyard", "labels": {"en": "Vineyards"}}],
|
|
240
|
+
}
|
|
241
|
+
client, rec = make(ok(catalog))
|
|
242
|
+
data = client.crop_catalog(lang="de")
|
|
243
|
+
assert rec.last.url.path == "/v1/reference/crops"
|
|
244
|
+
assert rec.last.url.params["lang"] == "de"
|
|
245
|
+
assert data["crops"][0]["useClass"] == "vineyard"
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def test_crop_catalog_without_lang_lets_the_api_choose():
|
|
249
|
+
client, rec = make(ok({"locale": "en", "crops": []}))
|
|
250
|
+
client.crop_catalog()
|
|
251
|
+
assert "lang" not in rec.last.url.params
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def test_crop_languages_are_the_ten_of_the_api():
|
|
255
|
+
assert CROP_LANGUAGES == ("es", "ca", "en", "pt", "fr", "it", "de", "pl", "nl", "cs")
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@pytest.mark.parametrize(
|
|
259
|
+
"call",
|
|
260
|
+
[
|
|
261
|
+
lambda c: c.parcels.subparcels("R"),
|
|
262
|
+
lambda c: c.parcels.neighbors("R"),
|
|
263
|
+
lambda c: c.locations.provinces(),
|
|
264
|
+
lambda c: c.locations.municipalities("CIUDAD REAL"),
|
|
265
|
+
lambda c: c.locations.streets("CIUDAD REAL", "AGUDO"),
|
|
266
|
+
],
|
|
267
|
+
)
|
|
268
|
+
def test_new_endpoints_raise_typed_errors_for_401_and_429(call):
|
|
269
|
+
client, _ = make(fail(401, "KEY_AUTH_002", "Invalid API key"))
|
|
270
|
+
with pytest.raises(AuthenticationError):
|
|
271
|
+
call(client)
|
|
272
|
+
|
|
273
|
+
client, rec = make(
|
|
274
|
+
fail(429, "KEY_AUTH_004", "Monthly quota used up (5000/5000).", headers={"X-Quota-Remaining": "0"})
|
|
275
|
+
)
|
|
276
|
+
with pytest.raises(QuotaExceededError) as info:
|
|
277
|
+
call(client)
|
|
278
|
+
assert info.value.quota["remaining"] == 0
|
|
279
|
+
assert len(rec.requests) == 1
|
|
280
|
+
|
|
281
|
+
client, _ = make(fail(429, "KEY_RATE_002", "Too many requests", headers={"Retry-After": "7"}))
|
|
282
|
+
with pytest.raises(RateLimitError) as limited:
|
|
283
|
+
call(client)
|
|
284
|
+
assert limited.value.retry_after == 7
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def test_quota_exhausted_on_subparcels_is_not_retried():
|
|
288
|
+
client, rec = make(fail(429, "KEY_AUTH_004", "Monthly quota used up"), max_retries=2)
|
|
289
|
+
with pytest.raises(QuotaExceededError):
|
|
290
|
+
client.parcels.subparcels("R")
|
|
291
|
+
assert len(rec.requests) == 1
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "2.0.0"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|