-
-
Notifications
You must be signed in to change notification settings - Fork 305
Add early support for JSON-FG #2136
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
francbartoli
wants to merge
8
commits into
geopython:master
Choose a base branch
from
francbartoli:feature/support-jsonfg
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+296
−5
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
82e9f3d
Add early implementation of items payload
francbartoli ba9511a
Fix payload for a single item
francbartoli 1e46834
Fix mime type and links for items and item id
francbartoli b25dc27
Fix missing links in items and item id
francbartoli 2359c2e
Add a basic test for the formatter
francbartoli 8103174
Fix flake8 errors
francbartoli 0d98f1d
Set gdal constraints for jsonfg
francbartoli ae0b39b
Force the build to fail until gdal 3.12 is available
francbartoli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| # ================================================================= | ||
| # | ||
| # Authors: Francesco Bartoli <xbartolone@gmail.com> | ||
| # | ||
| # Copyright (c) 2025 Francesco Bartoli | ||
| # | ||
| # Permission is hereby granted, free of charge, to any person | ||
| # obtaining a copy of this software and associated documentation | ||
| # files (the "Software"), to deal in the Software without | ||
| # restriction, including without limitation the rights to use, | ||
| # copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| # copies of the Software, and to permit persons to whom the | ||
| # Software is furnished to do so, subject to the following | ||
| # conditions: | ||
| # | ||
| # The above copyright notice and this permission notice shall be | ||
| # included in all copies or substantial portions of the Software. | ||
| # | ||
| # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | ||
| # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | ||
| # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | ||
| # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | ||
| # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
| # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | ||
| # OTHER DEALINGS IN THE SOFTWARE. | ||
| # | ||
| # ================================================================= | ||
| """JSON-FG capabilities | ||
| Returns content as JSON-FG representations | ||
| """ | ||
|
|
||
| import json | ||
| import logging | ||
| import uuid | ||
| from typing import Union | ||
|
|
||
| from osgeo import gdal | ||
|
|
||
| from pygeoapi.formatter.base import BaseFormatter, FormatterSerializationError | ||
|
|
||
|
|
||
| LOGGER = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class JSONFGFormatter(BaseFormatter): | ||
| """JSON-FG formatter""" | ||
|
|
||
| def __init__(self, formatter_def: dict): | ||
| """ | ||
| Initialize object | ||
|
|
||
| :param formatter_def: formatter definition | ||
|
|
||
| :returns: `pygeoapi.formatter.jsonfg.JSONFGFormatter` | ||
| """ | ||
|
|
||
| geom = False | ||
| if "geom" in formatter_def: | ||
| geom = formatter_def["geom"] | ||
|
|
||
| super().__init__({"name": "jsonfg", "geom": geom}) | ||
| self.mimetype = "application/geo+json" | ||
|
|
||
| def write( | ||
| self, data: dict, dataset: str, id_field: str, options: dict = {} | ||
| ) -> dict: | ||
| """ | ||
| Generate data in JSON-FG format | ||
|
|
||
| :param options: JSON-FG formatting options | ||
| :param data: dict of GeoJSON data | ||
|
|
||
| :returns: string representation of format | ||
| """ | ||
|
|
||
| try: | ||
| if data.get("features"): | ||
| fields = list(data["features"][0]["properties"].keys()) | ||
| else: | ||
| fields = data["properties"].keys() | ||
| except IndexError: | ||
| LOGGER.error("no features") | ||
| return dict() | ||
|
|
||
| LOGGER.debug(f"JSONFG fields: {fields}") | ||
|
|
||
| try: | ||
| links = data.get("links") | ||
| output = geojson2jsonfg(data=data, dataset=dataset) | ||
| output["links"] = links | ||
| return output | ||
| except ValueError as err: | ||
| LOGGER.error(err) | ||
| raise FormatterSerializationError("Error writing JSONFG output") | ||
|
|
||
| def __repr__(self): | ||
| return f"<JSONFGFormatter> {self.name}" | ||
|
|
||
|
|
||
| def geojson2jsonfg( | ||
| data: dict, | ||
| dataset: str, | ||
| identifier: Union[str, None] = None, | ||
| id_field: str = "id", | ||
| ) -> dict: | ||
| """ | ||
| Return JSON-FG from a GeoJSON content. | ||
|
|
||
| :param data: dict of data | ||
| :param dataset: dataset name | ||
| :param identifier: identifier field name | ||
| :param id_field: id field name | ||
|
|
||
| :returns: dict of converted GeoJSON (JSON-FG) | ||
| """ | ||
| gdal.UseExceptions() | ||
| LOGGER.debug("Dump GeoJSON content into a data source") | ||
| try: | ||
| with gdal.OpenEx(json.dumps(data)) as srcDS: | ||
| tmpfile = f"/vsimem/{uuid.uuid1()}.json" | ||
| LOGGER.debug("Translate GeoJSON into a JSONFG memory file") | ||
| gdal.VectorTranslate(tmpfile, srcDS, format="JSONFG") | ||
| LOGGER.debug("Read JSONFG content from a memory file") | ||
| data = gdal.VSIFOpenL(tmpfile, "rb") | ||
| if not data: | ||
| raise ValueError("Failed to read JSONFG content") | ||
| gdal.VSIFSeekL(data, 0, 2) | ||
| length = gdal.VSIFTellL(data) | ||
| gdal.VSIFSeekL(data, 0, 0) | ||
| jsonfg = json.loads(gdal.VSIFReadL(1, length, data).decode()) | ||
| return jsonfg | ||
| except Exception as e: | ||
| LOGGER.error(f"Failed to convert GeoJSON to JSON-FG: {e}") | ||
| raise | ||
| finally: | ||
| gdal.VSIFCloseL(data) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,7 +4,6 @@ cftime | |
| elasticsearch | ||
| elasticsearch-dsl | ||
| fiona | ||
| GDAL<=3.11.3 | ||
| geoalchemy2 | ||
| geopandas | ||
| netCDF4 | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,6 +2,7 @@ Babel | |
| click | ||
| filelock | ||
| Flask | ||
| GDAL>=3.12.0,<4.0.0 | ||
| jinja2 | ||
| jsonschema | ||
| pydantic | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| # ================================================================= | ||
| # | ||
| # Authors: Francesco Bartoli <xbartolone@gmail.com> | ||
| # | ||
| # Copyright (c) 2025 Francesco Bartoli | ||
| # | ||
| # Permission is hereby granted, free of charge, to any person | ||
| # obtaining a copy of this software and associated documentation | ||
| # files (the "Software"), to deal in the Software without | ||
| # restriction, including without limitation the rights to use, | ||
| # copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| # copies of the Software, and to permit persons to whom the | ||
| # Software is furnished to do so, subject to the following | ||
| # conditions: | ||
| # | ||
| # The above copyright notice and this permission notice shall be | ||
| # included in all copies or substantial portions of the Software. | ||
| # | ||
| # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | ||
| # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | ||
| # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | ||
| # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | ||
| # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
| # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | ||
| # OTHER DEALINGS IN THE SOFTWARE. | ||
| # | ||
| # ================================================================= | ||
|
|
||
| import pytest | ||
|
|
||
| from pygeoapi.formatter.jsonfg import JSONFGFormatter | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| def fixture(): | ||
| data = { | ||
| 'type': 'FeatureCollection', | ||
| 'features': [{ | ||
| 'type': 'Feature', | ||
| 'id': '123-456', | ||
| 'geometry': { | ||
| 'type': 'Point', | ||
| 'coordinates': [125.6, 10.1]}, | ||
| 'properties': { | ||
| 'name': 'Dinagat Islands', | ||
| 'foo': 'bar' | ||
| }} | ||
| ], | ||
| 'links': [{ | ||
| 'rel': 'self', | ||
| 'type': 'application/geo+json', | ||
| 'title': 'GeoJSON', | ||
| 'href': 'http://example.com' | ||
| }] | ||
| } | ||
|
|
||
| return data | ||
|
|
||
|
|
||
| def test_jsonfg__formatter(fixture): | ||
| f = JSONFGFormatter({'geom': True}) | ||
| f_jsonfg = f.write(data=fixture, dataset='test', id_field='id', options={}) | ||
|
|
||
| assert f.mimetype == "application/geo+json" | ||
|
|
||
| assert f_jsonfg['type'] == 'FeatureCollection' | ||
| assert f_jsonfg['features'][0]['type'] == 'Feature' | ||
| assert f_jsonfg['features'][0]['geometry']['type'] == 'Point' | ||
| assert f_jsonfg['features'][0]['geometry']['coordinates'] == [125.6, 10.1] | ||
| assert f_jsonfg['features'][0]['properties']['id'] == '123-456' | ||
| assert f_jsonfg['features'][0]['properties']['name'] == 'Dinagat Islands' | ||
| assert f_jsonfg['features'][0]['properties']['foo'] == 'bar' | ||
|
|
||
| assert f_jsonfg['featureType'] == 'OGRGeoJSON' | ||
| assert f_jsonfg['conformsTo'] | ||
| assert f_jsonfg['coordRefSys'] == '[EPSG:4326]' | ||
| assert f_jsonfg['features'][0]['place'] is None | ||
| assert f_jsonfg['features'][0]['time'] is None | ||
|
|
||
| assert len(f_jsonfg['links']) == 1 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Well once you read it into GDAL, any vector driver transform can occur. Wondering if would be possible to make any output format in the same spirit of the OGR provider - formatter config only barrier to add Shapefile, KML, etc. as an output format for pygeoapi GeoJSON.