Skip to content
Open
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
1 change: 1 addition & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ CACHE_BUSTING_STATIC_ENABLED=False
MAX_DOCUMENT_SIZE=200
CLIENT_RESULTS_LIMIT=5
API_LIMIT_PER_PAGE=1000
REST_API_V3_MAX_PAGE_SIZE=200

# GIS Client
GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY=mapstore
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ jobs:
with:
suite_name: "REST API Tests"
test_command: >
./test.sh geonode.api.tests geonode.base.api.tests geonode.layers.api.tests
./test.sh geonode.api.tests geonode.api.v3.tests geonode.base.api.tests geonode.layers.api.tests
geonode.maps.api.tests geonode.documents.api.tests geonode.geoapps.api.tests --duration=30 --failfast

csw:
Expand Down
7 changes: 7 additions & 0 deletions docs/src/setup/configuration/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -1416,6 +1416,13 @@ With this configuration, when a user creates a resource, GeoNode assigns the res

If ``RESOURCE_OWNERSHIP_ADMIN_USERNAME`` is not set, GeoNode defaults to ``admin``.

**REST_API_V3_MAX_PAGE_SIZE**

: - Default ``200``
- Env: ``REST_API_V3_MAX_PAGE_SIZE``

Upper bound of the ``page_size`` query parameter on API v3. A bigger value is clamped to this one. The default page size is ``REST_API_DEFAULT_PAGE_SIZE``.


## S

Expand Down
22 changes: 22 additions & 0 deletions geonode/api/v3/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#########################################################################
#
# Copyright (C) 2026 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
"""
GeoNode REST API v3: plain Django REST Framework, no dynamic-rest.
Viewsets extend V3GenericViewSet and are registered by hand in geonode.api.v3.urls
"""
21 changes: 21 additions & 0 deletions geonode/api/v3/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#########################################################################
#
# Copyright (C) 2026 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
# shared by serializers, viewsets and schema: schema.py cannot import viewsets.py, which imports it back
FIELDS_PARAM = "fields"
CONTEXT_KEY = "only_fields"
60 changes: 60 additions & 0 deletions geonode/api/v3/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#########################################################################
#
# Copyright (C) 2026 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
from http import HTTPStatus

from django.core.exceptions import PermissionDenied
from django.http import Http404
from rest_framework import exceptions
from rest_framework.views import exception_handler

PROBLEM_CONTENT_TYPE = "application/problem+json"


class Conflict(exceptions.APIException):
status_code = 409
default_detail = "The request conflicts with the current state of the resource."
default_code = "conflict"


def problem_details_handler(exc, context):
"""
Renders the errors raised in v3 views as RFC 9457 Problem Details.
Errors raised outside DRF (middlewares, unhandled exceptions) keep the Django rendering
"""
# the Http404 message names the model, the client only gets the generic one
if isinstance(exc, Http404):
exc = exceptions.NotFound()
elif isinstance(exc, PermissionDenied):
exc = exceptions.PermissionDenied(*exc.args)
response = exception_handler(exc, context)
if response is None:
return None
# as in v2: with a Basic challenge the browser pops its login dialog on an expired session
response.headers.pop("WWW-Authenticate", None)
_problem = {"type": "about:blank", "title": HTTPStatus(response.status_code).phrase, "status": response.status_code}
if isinstance(exc, exceptions.ValidationError):
_problem |= {"detail": str(exceptions.ValidationError.default_detail), "code": "invalid", "errors": exc.detail}
else:
_problem |= {"detail": str(exc.detail), "code": exc.get_codes()}
response.data = _problem
_request = context.get("request")
# the browsable API keeps its HTML, only JSON clients get the problem media type
if getattr(getattr(_request, "accepted_renderer", None), "format", None) == "json":
response.content_type = PROBLEM_CONTENT_TYPE
return response
9 changes: 9 additions & 0 deletions geonode/api/v3/openapi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
openapi: 3.0.3
info:
title: GeoNode API v3
version: 3.0.0
description: 'Version 3 of the GeoNode REST API. Plain Django REST Framework: field
selection is the single `fields` query parameter, and a trailing slash is required
on every path.'
paths: {}
components: {}
34 changes: 34 additions & 0 deletions geonode/api/v3/pagination.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#########################################################################
#
# Copyright (C) 2026 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
from django.conf import settings
from rest_framework.pagination import PageNumberPagination


class V3Pagination(PageNumberPagination):
"""Page-number pagination with a hard upper bound, a bigger ``page_size`` is clamped by DRF"""

page_size_query_param = "page_size"

@property
def page_size(self) -> int:
return int(settings.REST_API_DEFAULT_PAGE_SIZE)

@property
def max_page_size(self) -> int:
return int(settings.REST_API_V3_MAX_PAGE_SIZE)
119 changes: 119 additions & 0 deletions geonode/api/v3/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#########################################################################
#
# Copyright (C) 2026 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
"""
OpenAPI schema generation, scoped to v3.
drf-spectacular asserts that every view it walks carries its ``AutoSchema``: there is no global
``DEFAULT_SCHEMA_CLASS``, and ``exclude_non_v3_endpoints`` keeps only the v3 views
"""

import inspect
import logging

from drf_spectacular.contrib.rest_polymorphic import DjangoPolymorphicSerializerExtension
from drf_spectacular.openapi import AutoSchema
from drf_spectacular.utils import OpenApiParameter, extend_schema

from geonode.api.v3.constants import FIELDS_PARAM

logger = logging.getLogger(__name__)

V3_PATH_PREFIX = "/api/v3/"
SCHEMA_PATH_PREFIX = "/api/v3/schema/"

# polymorphic.contrib.drf is not installed: the extension would only warn and fail --fail-on-warn
DjangoPolymorphicSerializerExtension.optional = True


def exclude_non_v3_endpoints(endpoints, **kwargs):
"""Keep the views under /api/v3/ carrying V3AutoSchema, any other is left out with a warning"""
_kept = []
for _endpoint in endpoints:
_path, _callback = _endpoint[0], _endpoint[3]
# the schema views live under /api/v3/ but describe the API, they are not part of it
if not _path.startswith(V3_PATH_PREFIX) or _path.startswith(SCHEMA_PATH_PREFIX):
continue
if not issubclass(_schema_class(_callback), V3AutoSchema):
logger.warning(f"{_path} is left out of the API v3 schema: its view is not a V3GenericViewSet")
continue
_kept.append(_endpoint)
return _kept


def _schema_class(callback) -> type:
# an action documented with extend_v3_schema carries its own schema class
_schema = getattr(callback, "initkwargs", {}).get("schema") or getattr(
getattr(callback, "cls", None), "schema", None
)
return _schema if inspect.isclass(_schema) else type(_schema)


class V3AutoSchema(AutoSchema):
"""Documents the ``?fields=`` parameter, which no generator can infer, and the stability of the endpoint"""

def get_description(self):
_description = super().get_description()
if not (_stability := getattr(self.view, "stability", None)):
return _description
return "\n\n".join(_part for _part in (_description, f"Stability: {_stability}.") if _part)

def get_extensions(self):
_extensions = super().get_extensions()
if _stability := getattr(self.view, "stability", None):
_extensions = {**_extensions, "x-stability": _stability}
return _extensions

def get_override_parameters(self):
_parameters = list(super().get_override_parameters())
if self.method != "GET" or not hasattr(self.view, "get_requested_fields"):
return _parameters

_serializer_class = self.view.get_serializer_class()
if not hasattr(_serializer_class, "available_field_names"):
return _parameters

_description = "Subset of the fields to return, unknown names are rejected with 400."
if (_default := _serializer_class.default_field_names()) is not None:
_description = f"{_description} Default: {', '.join(sorted(_default))}."
_parameters.append(
OpenApiParameter(
name=FIELDS_PARAM,
type=str,
many=True,
enum=sorted(_serializer_class.available_field_names()),
style="form",
explode=False,
location=OpenApiParameter.QUERY,
required=False,
description=_description,
)
)
return _parameters


def extend_v3_schema(**kwargs):
"""``extend_schema`` for the methods and actions of v3 viewsets"""

def decorator(f):
# drf-spectacular extends DEFAULT_SCHEMA_CLASS, which v3 leaves unset so that v2 is never inspected
if not hasattr(f, "kwargs"):
f.kwargs = {}
f.kwargs.setdefault("schema", V3AutoSchema)
return extend_schema(**kwargs)(f)

return decorator
80 changes: 80 additions & 0 deletions geonode/api/v3/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#########################################################################
#
# Copyright (C) 2026 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
import typing

from rest_framework import serializers

from geonode.api.v3.constants import CONTEXT_KEY


class FieldSelectionMixin:
"""
Narrows the output to the fields asked with ``?fields=``.
Only the root serializer reads the requested set, a nested one returns its own ``Meta.default_fields``
"""

def __init__(self, *args, only_fields=None, **kwargs):
self._only_fields = set(only_fields) if only_fields is not None else None
super().__init__(*args, **kwargs)

@classmethod
def available_field_names(cls) -> typing.Set[str]:
"""The fields a read can return: write-only ones never appear in a response"""
return {_name for _name, _field in cls().get_fields().items() if not _field.write_only}

@classmethod
def default_field_names(cls) -> typing.Optional[typing.Set[str]]:
"""The fields returned when ``?fields=`` is absent, ``None`` means all of them"""
_default = getattr(getattr(cls, "Meta", None), "default_fields", None)
return set(_default) if _default is not None else None

def get_fields(self):
_fields = super().get_fields()
if (_selected := self.__selected_field_names()) is None:
return _fields
return {_name: _field for _name, _field in _fields.items() if _name in _selected}

def __selected_field_names(self) -> typing.Optional[typing.Set[str]]:
if self._only_fields is not None:
return self._only_fields
# the viewset sets the key on reads only, so writes always validate the full serializer
if CONTEXT_KEY not in self.context:
return None
# the context is shared with nested serializers, the requested names belong to the root only
if self.__is_root():
return self.context[CONTEXT_KEY]
return self.default_field_names()

def __is_root(self) -> bool:
if self.parent is None:
return True
return isinstance(self.parent, serializers.ListSerializer) and self.parent.parent is None


class FieldSelectionSerializer(FieldSelectionMixin, serializers.Serializer):
"""A serializer narrowed by ``?fields=``, for data not read from a model"""


class FieldSelectionModelSerializer(FieldSelectionMixin, serializers.ModelSerializer):
"""A model serializer narrowed by ``?fields=``, which also prepares the queryset its selected fields need"""

@classmethod
def setup_queryset(cls, queryset, fields: typing.Set[str], request):
"""Return the queryset with the joins and annotations needed by ``fields``, a nested serializer reuses it"""
return queryset
Empty file.
Loading
Loading