Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions pygeoapi/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
F_JSON = 'json'
F_COVERAGEJSON = 'json'
F_HTML = 'html'
F_JSONFG = 'jsonfg'
F_JSONLD = 'jsonld'
F_GZIP = 'gzip'
F_PNG = 'png'
Expand All @@ -94,7 +95,7 @@
(F_HTML, 'text/html'),
(F_JSONLD, 'application/ld+json'),
(F_JSON, 'application/json'),
(F_PNG, 'image/png'),
(F_JSONFG, 'application/geo+json'),
(F_JPEG, 'image/jpeg'),
(F_MVT, 'application/vnd.mapbox-vector-tile'),
(F_NETCDF, 'application/x-netcdf'),
Expand All @@ -108,7 +109,7 @@
'http://www.opengis.net/spec/ogcapi-common-2/1.0/conf/collections',
'http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/landing-page',
'http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/json',
'http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/html',
'http://www.opengis.net/spec/json-fg-1/0.3/conf/core',
'http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/oas30'
]

Expand Down Expand Up @@ -1127,6 +1128,12 @@ def describe_collections(api: API, request: APIRequest,
'title': l10n.translate('Items as GeoJSON', request.locale), # noqa
'href': f'{api.get_collections_url()}/{k}/items?f={F_JSON}' # noqa
})
collection['links'].append({
'type': FORMAT_TYPES[F_JSONFG],
'rel': 'items',
'title': l10n.translate('Items as JSON-FG', request.locale), # noqa
'href': f'{api.get_collections_url()}/{k}/items?f={F_JSONFG}' # noqa
})
collection['links'].append({
'type': FORMAT_TYPES[F_JSONLD],
'rel': 'items',
Expand Down Expand Up @@ -1333,6 +1340,12 @@ def describe_collections(api: API, request: APIRequest,
'title': l10n.translate('This document as JSON', request.locale), # noqa
'href': f'{api.get_collections_url()}?f={F_JSON}'
})
fcm['links'].append({
'type': FORMAT_TYPES[F_JSONFG],
'rel': request.get_linkrel(F_JSONFG),
'title': l10n.translate('This document as JSON-FG', request.locale), # noqa
'href': f'{api.get_collections_url()}?f={F_JSONFG}'
})
fcm['links'].append({
'type': FORMAT_TYPES[F_JSONLD],
'rel': request.get_linkrel(F_JSONLD),
Expand Down
61 changes: 60 additions & 1 deletion pygeoapi/api/itemtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@
to_json, transform_bbox)

from . import (
APIRequest, API, SYSTEM_LOCALE, F_JSON, FORMAT_TYPES, F_HTML, F_JSONLD,
APIRequest, API, SYSTEM_LOCALE, F_JSON,
FORMAT_TYPES, F_HTML, F_JSONFG, F_JSONLD,
validate_bbox, validate_datetime
)

Expand Down Expand Up @@ -573,6 +574,11 @@ def get_collection_items(
'rel': request.get_linkrel(F_JSON),
'title': l10n.translate('This document as GeoJSON', request.locale),
'href': f'{uri}?f={F_JSON}{serialized_query_params}'
}, {
'rel': request.get_linkrel(F_JSONFG),
'type': FORMAT_TYPES[F_JSONFG],
'title': l10n.translate('This document as JSON-FG', request.locale), # noqa
'href': f'{uri}?f={F_JSONFG}{serialized_query_params}'
}, {
'rel': request.get_linkrel(F_JSONLD),
'type': FORMAT_TYPES[F_JSONLD],
Expand Down Expand Up @@ -698,6 +704,31 @@ def get_collection_items(

return headers, HTTPStatus.OK, content

elif request.format == F_JSONFG:
formatter = load_plugin('formatter',
{'name': F_JSONFG, 'geom': True})

try:
content = formatter.write(
data=content,
dataset=dataset,
id_field=(p.uri_field or 'id'),
options={
'provider_def': get_provider_by_type(
collections[dataset]['providers'],
'feature')
}
)
except FormatterSerializationError:
msg = 'Error serializing output'
return api.get_exception(
HTTPStatus.INTERNAL_SERVER_ERROR, headers, request.format,
'NoApplicableCode', msg)

headers['Content-Type'] = formatter.mimetype

return headers, HTTPStatus.OK, to_json(content, api.pretty_print)

return headers, HTTPStatus.OK, to_json(content, api.pretty_print)


Expand Down Expand Up @@ -920,6 +951,11 @@ def get_collection_item(api: API, request: APIRequest,
'title': l10n.translate('This document as JSON', request.locale),
'href': f'{uri}?f={F_JSON}'
}, {
'rel': request.get_linkrel(F_JSONFG),
'type': FORMAT_TYPES[F_JSONFG],
'title': l10n.translate('This document as JSON-FG (JSON-FG)', request.locale), # noqa
'href': f'{uri}?f={F_JSONFG}'
}, {
'rel': request.get_linkrel(F_JSONLD),
'type': FORMAT_TYPES[F_JSONLD],
'title': l10n.translate('This document as RDF (JSON-LD)', request.locale), # noqa
Expand Down Expand Up @@ -982,6 +1018,29 @@ def get_collection_item(api: API, request: APIRequest,

return headers, HTTPStatus.OK, content

elif request.format == F_JSONFG:
formatter = load_plugin('formatter',
{'name': F_JSONFG, 'geom': True})

try:
content = formatter.write(
data=content,
dataset=dataset,
id_field=(p.uri_field or 'id'),
options={
'provider_def': get_provider_by_type(
collections[dataset]['providers'],
'feature')
}
)
except FormatterSerializationError:
msg = 'Error serializing output'
return api.get_exception(
HTTPStatus.INTERNAL_SERVER_ERROR, headers, request.format,
'NoApplicableCode', msg)

return headers, HTTPStatus.OK, to_json(content, api.pretty_print)

return headers, HTTPStatus.OK, to_json(content, api.pretty_print)


Expand Down
137 changes: 137 additions & 0 deletions pygeoapi/formatter/jsonfg.py
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")
Copy link
Member

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.

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)
3 changes: 2 additions & 1 deletion pygeoapi/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@
'xarray-edr': 'pygeoapi.provider.xarray_edr.XarrayEDRProvider'
},
'formatter': {
'CSV': 'pygeoapi.formatter.csv_.CSVFormatter'
'CSV': 'pygeoapi.formatter.csv_.CSVFormatter',
'jsonfg': 'pygeoapi.formatter.jsonfg.JSONFGFormatter',
},
'process': {
'HelloWorld': 'pygeoapi.process.hello_world.HelloWorldProcessor',
Expand Down
1 change: 0 additions & 1 deletion requirements-provider.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ cftime
elasticsearch
elasticsearch-dsl
fiona
GDAL<=3.11.3
geoalchemy2
geopandas
netCDF4
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ Babel
click
filelock
Flask
GDAL>=3.12.0,<4.0.0
jinja2
jsonschema
pydantic
Expand Down
81 changes: 81 additions & 0 deletions tests/formatter/test_jsonfg__formatter.py
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
Loading