diff --git a/.env.sample b/.env.sample index a43b3f34b51..72263b9a3a8 100644 --- a/.env.sample +++ b/.env.sample @@ -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 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c60bdd55395..1f688eb2d2d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -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: diff --git a/docs/src/setup/configuration/settings.md b/docs/src/setup/configuration/settings.md index b03734d3483..45e2150951d 100644 --- a/docs/src/setup/configuration/settings.md +++ b/docs/src/setup/configuration/settings.md @@ -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 diff --git a/geonode/api/v3/__init__.py b/geonode/api/v3/__init__.py new file mode 100644 index 00000000000..d791e73cd58 --- /dev/null +++ b/geonode/api/v3/__init__.py @@ -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 . +# +######################################################################### +""" +GeoNode REST API v3: plain Django REST Framework, no dynamic-rest. +Viewsets extend V3GenericViewSet and are registered by hand in geonode.api.v3.urls +""" diff --git a/geonode/api/v3/constants.py b/geonode/api/v3/constants.py new file mode 100644 index 00000000000..87b5e6fd38d --- /dev/null +++ b/geonode/api/v3/constants.py @@ -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 . +# +######################################################################### +# shared by serializers, viewsets and schema: schema.py cannot import viewsets.py, which imports it back +FIELDS_PARAM = "fields" +CONTEXT_KEY = "only_fields" diff --git a/geonode/api/v3/exceptions.py b/geonode/api/v3/exceptions.py new file mode 100644 index 00000000000..3243da83f64 --- /dev/null +++ b/geonode/api/v3/exceptions.py @@ -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 . +# +######################################################################### +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 diff --git a/geonode/api/v3/openapi.yaml b/geonode/api/v3/openapi.yaml new file mode 100644 index 00000000000..a9445b1bc39 --- /dev/null +++ b/geonode/api/v3/openapi.yaml @@ -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: {} diff --git a/geonode/api/v3/pagination.py b/geonode/api/v3/pagination.py new file mode 100644 index 00000000000..5d0bad1fa31 --- /dev/null +++ b/geonode/api/v3/pagination.py @@ -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 . +# +######################################################################### +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) diff --git a/geonode/api/v3/schema.py b/geonode/api/v3/schema.py new file mode 100644 index 00000000000..afe090bb235 --- /dev/null +++ b/geonode/api/v3/schema.py @@ -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 . +# +######################################################################### +""" +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 diff --git a/geonode/api/v3/serializers.py b/geonode/api/v3/serializers.py new file mode 100644 index 00000000000..9763db2795f --- /dev/null +++ b/geonode/api/v3/serializers.py @@ -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 . +# +######################################################################### +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 diff --git a/geonode/api/v3/tests/__init__.py b/geonode/api/v3/tests/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/geonode/api/v3/tests/test_exceptions.py b/geonode/api/v3/tests/test_exceptions.py new file mode 100644 index 00000000000..387ff4a0790 --- /dev/null +++ b/geonode/api/v3/tests/test_exceptions.py @@ -0,0 +1,81 @@ +######################################################################### +# +# 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 . +# +######################################################################### +from django.contrib.auth.models import Group +from django.test import SimpleTestCase, TestCase +from rest_framework.test import APIRequestFactory + +from geonode.api.v3.exceptions import Conflict, problem_details_handler +from geonode.api.v3.tests.utils import GROUP_PREFIX, GroupViewSet, ReadOnlyGroupViewSet + + +class ProblemDetailsHandlerTest(SimpleTestCase): + def test_api_exceptions_should_become_problem_details(self): + response = problem_details_handler(Conflict("The thing is in use."), {}) + expected = {"type": "about:blank", "title": "Conflict", "status": 409, "detail": "The thing is in use."} + self.assertDictEqual({**expected, "code": "conflict"}, response.data) + + def test_errors_raised_outside_drf_should_be_left_to_django(self): + self.assertIsNone(problem_details_handler(ValueError("boom"), {})) + + +class ProblemDetailsViewTest(TestCase): + def setUp(self): + self.factory = APIRequestFactory() + + def tearDown(self): + Group.objects.filter(name__startswith=GROUP_PREFIX).delete() + + def test_validation_errors_should_be_kept_by_field(self): + response = GroupViewSet.as_view({"get": "list"})(self.factory.get("/?fields=foo")).render() + expected = { + "type": "about:blank", + "title": "Bad Request", + "status": 400, + "detail": "Invalid input.", + "code": "invalid", + "errors": {"fields": ["Unknown field(s): foo. Available: id, name, user_count."]}, + } + self.assertDictEqual(expected, response.data) + self.assertEqual("application/problem+json", response["Content-Type"]) + + def test_authentication_errors_should_be_problem_details(self): + response = ReadOnlyGroupViewSet.as_view({"get": "list"})(self.factory.get("/")).render() + expected = { + "type": "about:blank", + "title": "Unauthorized", + "status": 401, + "detail": "Authentication credentials were not provided.", + "code": "not_authenticated", + } + self.assertDictEqual(expected, response.data) + # as in v2, so an expired session never pops the browser login dialog + self.assertEqual(401, response.status_code) + self.assertNotIn("WWW-Authenticate", response) + + def test_not_found_should_be_problem_details(self): + response = GroupViewSet.as_view({"get": "retrieve"})(self.factory.get("/"), pk=0).render() + self.assertEqual(404, response.status_code) + expected = {"type": "about:blank", "title": "Not Found", "status": 404, "detail": "Not found."} + self.assertDictEqual({**expected, "code": "not_found"}, response.data) + + def test_browsable_api_should_keep_its_html(self): + request = self.factory.get("/?fields=foo", HTTP_ACCEPT="text/html") + response = GroupViewSet.as_view({"get": "list"})(request).render() + self.assertEqual(400, response.status_code) + self.assertTrue(response["Content-Type"].startswith("text/html")) diff --git a/geonode/api/v3/tests/test_infrastructure.py b/geonode/api/v3/tests/test_infrastructure.py new file mode 100644 index 00000000000..1ef3fe0f316 --- /dev/null +++ b/geonode/api/v3/tests/test_infrastructure.py @@ -0,0 +1,238 @@ +######################################################################### +# +# 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 . +# +######################################################################### +from unittest.mock import ANY, patch + +from django.conf import settings +from django.contrib.auth.models import Group +from django.test import SimpleTestCase, TestCase, override_settings +from django.contrib.auth import get_user_model +from django.urls import resolve, reverse +from rest_framework import serializers +from rest_framework.permissions import AllowAny, IsAuthenticated +from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer +from rest_framework.request import Request +from rest_framework.test import APIClient, APIRequestFactory, force_authenticate + +from geonode.api.v3.constants import CONTEXT_KEY +from geonode.api.v3.pagination import V3Pagination +from geonode.api.v3.tests.utils import ( + GROUP_PREFIX, + CountingGroupSerializer, + GroupSerializer, + GroupViewSet, + NestingSerializer, + PlainGroupViewSet, + ReadOnlyGroupViewSet, +) +from geonode.api.v3.urls import router +from geonode.api.v3.viewsets import V3GenericViewSet + + +class FieldSelectionSerializerTest(SimpleTestCase): + def setUp(self): + self.group = Group(id=7, name="g") + self.group.related_groups = [Group(id=8, name="h")] + + def test_available_field_names_should_ignore_narrowing(self): + self.assertSetEqual({"id", "name"}, GroupSerializer.available_field_names()) + + def test_available_field_names_should_leave_out_write_only_fields(self): + """A write-only field never appears in a response, it cannot be selected""" + + class _WriteOnlySerializer(GroupSerializer): + secret = serializers.CharField(write_only=True) + + class Meta(GroupSerializer.Meta): + fields = ("id", "name", "secret") + + self.assertSetEqual({"id", "name"}, _WriteOnlySerializer.available_field_names()) + + def test_default_field_names_should_read_the_meta(self): + self.assertSetEqual({"id"}, GroupSerializer.default_field_names()) + self.assertIsNone(NestingSerializer.default_field_names()) + + def test_get_fields_should_return_all_fields_without_selection(self): + self.assertSetEqual({"id", "name"}, set(GroupSerializer().get_fields())) + + def test_only_fields_kwarg_should_narrow_the_output(self): + self.assertDictEqual({"id": 7}, GroupSerializer(self.group, only_fields={"id"}).data) + + def test_context_should_narrow_the_output(self): + self.assertDictEqual({"name": "g"}, GroupSerializer(self.group, context={CONTEXT_KEY: {"name"}}).data) + + def test_only_fields_kwarg_should_take_precedence_over_the_context(self): + serializer = GroupSerializer(self.group, only_fields={"id"}, context={CONTEXT_KEY: {"name"}}) + self.assertDictEqual({"id": 7}, serializer.data) + + def test_root_list_should_narrow_each_item(self): + serializer = GroupSerializer([self.group], many=True, context={CONTEXT_KEY: {"name"}}) + self.assertListEqual([{"name": "g"}], serializer.data) + + def test_nested_serializers_should_return_their_own_default_fields(self): + """The requested names belong to the root, the shared context must not narrow nested serializers""" + serializer = NestingSerializer(self.group, context={CONTEXT_KEY: {"id", "nested", "nested_list"}}) + expected = {"id": 7, "nested": {"id": 7}, "nested_list": [{"id": 8}]} + self.assertDictEqual(expected, serializer.data) + + def test_nested_serializers_should_return_all_fields_on_writes(self): + expected = {"id": 7, "name": "g", "nested": {"id": 7, "name": "g"}, "nested_list": [{"id": 8, "name": "h"}]} + self.assertDictEqual(expected, NestingSerializer(self.group).data) + + +class FieldSelectionViewSetTest(TestCase): + def setUp(self): + self.factory = APIRequestFactory() + self.group = Group.objects.create(name=f"{GROUP_PREFIX}one") + + def tearDown(self): + Group.objects.filter(name__startswith=GROUP_PREFIX).delete() + + def _list(self, query="", viewset=GroupViewSet): + return viewset.as_view({"get": "list"})(self.factory.get(f"/{query}")) + + def test_list_should_return_the_default_fields(self): + response = self._list() + self.assertEqual(200, response.status_code, response.data) + self.assertListEqual([{"id": self.group.pk, "user_count": 0}], response.data["results"]) + + def test_list_should_return_the_requested_fields(self): + response = self._list("?fields=name") + self.assertEqual(200, response.status_code, response.data) + self.assertListEqual([{"name": self.group.name}], response.data["results"]) + + def test_list_should_refuse_unknown_fields(self): + self.assertEqual(400, self._list("?fields=id,foo").status_code) + + def test_options_should_ignore_the_field_selection(self): + """OPTIONS describes the write serializer, which is never narrowed""" + response = GroupViewSet.as_view({"get": "list", "post": "create"})(self.factory.options("/?fields=foo")) + self.assertEqual(200, response.status_code, response.data) + self.assertSetEqual({"id", "name", "user_count"}, set(response.data["actions"]["POST"])) + + def test_setup_queryset_should_receive_the_selected_fields(self): + with patch.object( + CountingGroupSerializer, "setup_queryset", wraps=CountingGroupSerializer.setup_queryset + ) as _setup: + self._list("?fields=name") + _setup.assert_called_with(ANY, {"name"}, ANY) + + def test_fields_should_be_refused_if_the_serializer_cannot_select_them(self): + """Ignoring ?fields= would silently return every field""" + self.assertEqual(400, self._list("?fields=id", viewset=PlainGroupViewSet).status_code) + response = self._list(viewset=PlainGroupViewSet) + self.assertListEqual([{"id": self.group.pk, "name": self.group.name}], response.data["results"]) + + def test_create_should_answer_with_the_read_representation(self): + """The response is refetched, so the annotations of setup_queryset are there too""" + request = self.factory.post("/", {"name": f"{GROUP_PREFIX}two"}, format="json") + response = GroupViewSet.as_view({"post": "create"})(request) + self.assertEqual(201, response.status_code, response.data) + _created = Group.objects.get(name=f"{GROUP_PREFIX}two") + self.assertDictEqual({"id": _created.pk, "user_count": 0}, response.data) + + def test_create_should_validate_the_full_serializer(self): + response = GroupViewSet.as_view({"post": "create"})(self.factory.post("/", {}, format="json")) + self.assertEqual(400, response.status_code, response.data) + + def test_update_should_answer_with_the_read_representation(self): + request = self.factory.patch("/", {"name": f"{GROUP_PREFIX}renamed"}, format="json") + response = GroupViewSet.as_view({"patch": "partial_update"})(request, pk=self.group.pk) + self.assertEqual(200, response.status_code, response.data) + self.assertDictEqual({"id": self.group.pk, "user_count": 0}, response.data) + self.group.refresh_from_db() + self.assertEqual(f"{GROUP_PREFIX}renamed", self.group.name) + + +class V3GenericViewSetTest(TestCase): + def setUp(self): + self.factory = APIRequestFactory() + self.group = Group.objects.create(name=f"{GROUP_PREFIX}one") + self.user = get_user_model().objects.create(username=f"{GROUP_PREFIX}user") + + def tearDown(self): + Group.objects.filter(name__startswith=GROUP_PREFIX).delete() + self.user.delete() + + def test_permission_classes_should_fail_closed(self): + self.assertListEqual([IsAuthenticated], V3GenericViewSet.permission_classes) + + def test_anonymous_user_cannot_list_without_explicit_permission_classes(self): + response = ReadOnlyGroupViewSet.as_view({"get": "list"})(self.factory.get("/")) + self.assertEqual(401, response.status_code, response.data) + + def test_composed_viewset_should_select_fields(self): + """A viewset composed with only the DRF mixins it needs keeps the ?fields= contract""" + request = self.factory.get("/?fields=name") + force_authenticate(request, user=self.user) + response = ReadOnlyGroupViewSet.as_view({"get": "list"})(request) + self.assertEqual(200, response.status_code, response.data) + self.assertListEqual([{"name": self.group.name}], response.data["results"]) + + def test_renderers_should_not_come_from_dynamic_rest(self): + expected = [JSONRenderer, BrowsableAPIRenderer] + self.assertListEqual(expected, V3GenericViewSet.renderer_classes) + self.assertListEqual(expected, resolve(reverse("api_v3:api-root")).func.view_class.renderer_classes) + + +class V3PaginationTest(SimpleTestCase): + def _page_size(self, value): + return V3Pagination().get_page_size(Request(APIRequestFactory().get(f"/?page_size={value}"))) + + def test_page_size_should_be_bounded(self): + """v2 leaves MAX_PAGE_SIZE unset, v3 must not""" + self.assertEqual(settings.REST_API_V3_MAX_PAGE_SIZE, self._page_size(100000)) + + @override_settings(REST_API_V3_MAX_PAGE_SIZE=5) + def test_max_page_size_should_be_read_at_request_time(self): + self.assertEqual(5, self._page_size(50)) + + +class V3RouterTest(SimpleTestCase): + def test_trailing_slash_should_be_required(self): + self.assertEqual("/", router.trailing_slash) + + def test_registered_viewsets_should_not_allow_any(self): + """AllowAny makes an endpoint world-writable, a public read uses IsAuthenticatedOrReadOnly""" + offenders = [ + f"{prefix} -> {viewset.__name__}" + for prefix, viewset, _basename in router.registry + if not viewset.permission_classes or AllowAny in viewset.permission_classes + ] + self.assertListEqual([], offenders) + + def test_registered_prefixes_should_be_unique(self): + """DRF refuses a duplicate basename only, a duplicate prefix would be silently shadowed""" + _prefixes = [prefix for prefix, _viewset, _basename in router.registry] + self.assertListEqual(sorted(set(_prefixes)), sorted(_prefixes)) + + def test_every_registered_serializer_should_declare_known_default_fields(self): + offenders = [] + for prefix, viewset, _basename in router.registry: + _serializer_class = getattr(viewset, "serializer_class", None) + if not hasattr(_serializer_class, "default_field_names"): + continue + _default = _serializer_class.default_field_names() or set() + if _unknown := _default - _serializer_class.available_field_names(): + offenders.append(f"{prefix} -> {sorted(_unknown)}") + self.assertListEqual([], offenders) + + +class V3RootTest(TestCase): + def test_anonymous_user_can_read_the_root(self): + self.assertEqual(200, APIClient().get(reverse("api_v3:api-root")).status_code) diff --git a/geonode/api/v3/tests/test_schema.py b/geonode/api/v3/tests/test_schema.py new file mode 100644 index 00000000000..7b5c6de190e --- /dev/null +++ b/geonode/api/v3/tests/test_schema.py @@ -0,0 +1,168 @@ +######################################################################### +# +# 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 . +# +######################################################################### +import os +import tempfile + +from django.conf import settings +from django.core.management import call_command +from django.test import SimpleTestCase, TestCase +from django.urls import path, reverse +from drf_spectacular.generators import SchemaGenerator +from rest_framework.test import APIClient + +from geonode.api.v3.schema import V3AutoSchema, exclude_non_v3_endpoints +from drf_spectacular.views import SpectacularAPIView +from rest_framework.decorators import action +from rest_framework.views import APIView + +from geonode.api.v3.schema import extend_v3_schema +from geonode.api.v3.tests.utils import CountingGroupSerializer, GroupViewSet +from geonode.api.v3.urls import router +from geonode.api.v3.viewsets import V3GenericViewSet + + +class PlainView(APIView): + def get(self, request): + pass + + +class _ActionGroupViewSet(GroupViewSet): + @extend_v3_schema(responses=CountingGroupSerializer(many=True)) + @action(detail=True, methods=["get"]) + def related(self, request, pk=None): + pass + + +def generate(patterns=None): + return SchemaGenerator(patterns=patterns).get_schema(request=None, public=True) + + +class SchemaScopingTest(SimpleTestCase): + """Guards the exact failure that caused #14202""" + + def test_default_schema_class_should_not_be_global(self): + """Setting it globally is what dragged v2's dynamic-rest views into generation""" + self.assertNotIn("DEFAULT_SCHEMA_CLASS", settings.REST_FRAMEWORK) + + def test_v3_viewsets_should_carry_the_v3_autoschema(self): + for _prefix, viewset, _basename in router.registry: + self.assertTrue(issubclass(viewset, V3GenericViewSet), f"{viewset.__name__} is not a V3GenericViewSet") + self.assertIsInstance(V3GenericViewSet.schema, V3AutoSchema) + + def test_preprocessing_hook_should_drop_non_v3_paths(self): + _view = GroupViewSet.as_view({"get": "list"}) + endpoints = [ + ("/api/v3/groups/", None, "GET", _view), + ("/api/v2/resources/", None, "GET", _view), + ("/api/base/", None, "GET", _view), + ] + self.assertListEqual(["/api/v3/groups/"], [_path for _path, *_ in exclude_non_v3_endpoints(endpoints)]) + + def test_preprocessing_hook_should_drop_the_schema_views(self): + """SpectacularAPIView is under /api/v3/ but has no spectacular AutoSchema""" + endpoints = [ + ("/api/v3/groups/", None, "GET", GroupViewSet.as_view({"get": "list"})), + ("/api/v3/schema/", None, "GET", SpectacularAPIView.as_view()), + ] + self.assertListEqual(["/api/v3/groups/"], [_path for _path, *_ in exclude_non_v3_endpoints(endpoints)]) + + def test_preprocessing_hook_should_drop_the_views_without_the_v3_autoschema(self): + """A plugin view that is not a V3GenericViewSet would break the generation""" + endpoints = [ + ("/api/v3/groups/", None, "GET", GroupViewSet.as_view({"get": "list"})), + ("/api/v3/plain/", None, "GET", PlainView.as_view()), + ] + with self.assertLogs("geonode.api.v3.schema", level="WARNING") as _log: + kept = [_path for _path, *_ in exclude_non_v3_endpoints(endpoints)] + self.assertListEqual(["/api/v3/groups/"], kept) + self.assertIn("/api/v3/plain/", _log.output[0]) + + def test_preprocessing_hook_should_keep_the_actions_documented_with_extend_v3_schema(self): + _view = _ActionGroupViewSet.as_view({"get": "related"}, **_ActionGroupViewSet.related.kwargs) + kept = exclude_non_v3_endpoints([("/api/v3/groups/1/related/", None, "GET", _view)]) + self.assertEqual(1, len(kept)) + + +class SchemaGenerationTest(SimpleTestCase): + def test_metadata_should_reflect_the_v3_conventions(self): + schema = generate() + self.assertEqual("GeoNode API v3", schema["info"]["title"]) + self.assertEqual("3.0.0", schema["info"]["version"]) + self.assertTrue(all(_path.endswith("/") for _path in schema["paths"])) + + def test_fields_parameter_should_list_the_available_fields(self): + schema = generate([path("api/v3/groups/", GroupViewSet.as_view({"get": "list", "post": "create"}))]) + _operation = schema["paths"]["/api/v3/groups/"] + _fields = next(_param for _param in _operation["get"]["parameters"] if _param["name"] == "fields") + expected = { + "in": "query", + "name": "fields", + "schema": {"type": "array", "items": {"type": "string", "enum": ["id", "name", "user_count"]}}, + "description": "Subset of the fields to return, unknown names are rejected with 400. Default: id, user_count.", + "explode": False, + "style": "form", + } + self.assertDictEqual(expected, _fields) + self.assertNotIn("fields", [_param["name"] for _param in _operation["post"].get("parameters", [])]) + + def test_operations_should_carry_their_stability(self): + schema = generate([path("api/v3/groups/", GroupViewSet.as_view({"get": "list"}))]) + _operation = schema["paths"]["/api/v3/groups/"]["get"] + self.assertEqual("experimental", _operation["x-stability"]) + self.assertIn("Stability: experimental.", _operation["description"]) + + def test_extend_v3_schema_should_document_an_action_as_a_page(self): + """Plain extend_schema builds on the unset DEFAULT_SCHEMA_CLASS and breaks the generation""" + schema = generate([path("api/v3/groups//related/", _ActionGroupViewSet.as_view({"get": "related"}))]) + _operation = schema["paths"]["/api/v3/groups/{id}/related/"]["get"] + self.assertSetEqual( + {"fields", "id", "page", "page_size"}, {_param["name"] for _param in _operation["parameters"]} + ) + _schema = _operation["responses"]["200"]["content"]["application/json"]["schema"] + self.assertEqual("#/components/schemas/PaginatedCountingGroupList", _schema["$ref"]) + + +class SchemaSnapshotTest(SimpleTestCase): + def test_schema_should_match_the_committed_snapshot(self): + """ + Every API change shows up as a diff of openapi.yaml, regenerate it with the default LANGUAGE_CODE + (model verbose names end up in the descriptions): + manage.py spectacular --validate --fail-on-warn --file geonode/api/v3/openapi.yaml + """ + with tempfile.TemporaryDirectory() as _dir: + _file = os.path.join(_dir, "openapi.yaml") + call_command("spectacular", "--validate", "--fail-on-warn", "--file", _file) + with ( + open(_file) as _generated, + open(os.path.join(os.path.dirname(__file__), "..", "openapi.yaml")) as _snapshot, + ): + self.assertEqual( + _snapshot.read(), _generated.read(), self.test_schema_should_match_the_committed_snapshot.__doc__ + ) + + +class SchemaEndpointTest(TestCase): + def test_schema_endpoint_should_serve(self): + self.assertEqual(200, APIClient().get(reverse("api_v3:schema")).status_code) + + def test_swagger_and_redoc_should_render(self): + """#14201 was reported as 'redoc is broken', keep both reachable""" + for name in ("api_v3:swagger-ui", "api_v3:redoc"): + with self.subTest(view=name): + self.assertEqual(200, APIClient().get(reverse(name)).status_code) diff --git a/geonode/api/v3/tests/utils.py b/geonode/api/v3/tests/utils.py new file mode 100644 index 00000000000..6dad22acf8f --- /dev/null +++ b/geonode/api/v3/tests/utils.py @@ -0,0 +1,83 @@ +######################################################################### +# +# 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 . +# +######################################################################### +from django.contrib.auth.models import Group +from django.db.models import Count +from rest_framework import mixins, serializers +from rest_framework.permissions import AllowAny + +from geonode.api.v3.serializers import FieldSelectionModelSerializer +from geonode.api.v3.viewsets import V3GenericViewSet, V3ModelViewSet + +GROUP_PREFIX = "v3-test-" + + +class GroupSerializer(FieldSelectionModelSerializer): + class Meta: + model = Group + fields = ("id", "name") + default_fields = ("id",) + + +class NestingSerializer(FieldSelectionModelSerializer): + nested = GroupSerializer(source="*", read_only=True) + nested_list = GroupSerializer(source="related_groups", many=True, read_only=True) + + class Meta: + model = Group + fields = ("id", "name", "nested", "nested_list") + + +class CountingGroupSerializer(FieldSelectionModelSerializer): + user_count = serializers.IntegerField(read_only=True) + + class Meta: + model = Group + fields = ("id", "name", "user_count") + default_fields = ("id", "user_count") + + @classmethod + def setup_queryset(cls, queryset, fields, request): + if "user_count" in fields: + queryset = queryset.annotate(user_count=Count("user")) + return queryset + + +class GroupViewSet(V3ModelViewSet): + permission_classes = [AllowAny] + serializer_class = CountingGroupSerializer + + def get_base_queryset(self): + return Group.objects.filter(name__startswith=GROUP_PREFIX).order_by("id") + + +class PlainGroupSerializer(serializers.ModelSerializer): + class Meta: + model = Group + fields = ("id", "name") + + +class PlainGroupViewSet(GroupViewSet): + serializer_class = PlainGroupSerializer + + +class ReadOnlyGroupViewSet(mixins.ListModelMixin, V3GenericViewSet): + serializer_class = CountingGroupSerializer + + def get_base_queryset(self): + return Group.objects.filter(name__startswith=GROUP_PREFIX).order_by("id") diff --git a/geonode/api/v3/urls.py b/geonode/api/v3/urls.py new file mode 100644 index 00000000000..8ea2bc296fd --- /dev/null +++ b/geonode/api/v3/urls.py @@ -0,0 +1,45 @@ +######################################################################### +# +# 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 . +# +######################################################################### +""" +The only place where v3 routes are registered: import the viewset and register it here by hand. +Keep the prefixes alphabetical, so the root stays readable +""" + +from django.urls import include, path +from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView +from rest_framework.routers import DefaultRouter + +from geonode.api.v3.viewsets import V3RootView + +app_name = "api_v3" + + +class V3Router(DefaultRouter): + APIRootView = V3RootView + + +router = V3Router(trailing_slash=True) + +urlpatterns = [ + # url_name is namespaced because this module sets app_name + path("schema/", SpectacularAPIView.as_view(), name="schema"), + path("schema/swagger-ui/", SpectacularSwaggerView.as_view(url_name="api_v3:schema"), name="swagger-ui"), + path("schema/redoc/", SpectacularRedocView.as_view(url_name="api_v3:schema"), name="redoc"), + path("", include(router.urls)), +] diff --git a/geonode/api/v3/viewsets.py b/geonode/api/v3/viewsets.py new file mode 100644 index 00000000000..64d029192d2 --- /dev/null +++ b/geonode/api/v3/viewsets.py @@ -0,0 +1,179 @@ +######################################################################### +# +# 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 . +# +######################################################################### +import typing + +from rest_framework import mixins, viewsets +from rest_framework.exceptions import ValidationError +from rest_framework.permissions import AllowAny, IsAuthenticated +from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer +from rest_framework.response import Response +from rest_framework.routers import APIRootView + +from geonode.api.v3.constants import CONTEXT_KEY, FIELDS_PARAM +from geonode.api.v3.exceptions import problem_details_handler +from geonode.api.v3.pagination import V3Pagination +from geonode.api.v3.schema import V3AutoSchema + +_UNSET = object() + +# OPTIONS is safe too, but its metadata describes the write serializer, which is never narrowed +READ_METHODS = ("GET", "HEAD") + +# the global default browsable renderer comes from dynamic-rest, v3 is plain DRF +V3_RENDERER_CLASSES = [JSONRenderer, BrowsableAPIRenderer] + + +class FieldSelectionViewSetMixin: + """ + Implements ``?fields=`` on both the serializer and the queryset. + The serializer declares what its fields cost in ``setup_queryset``, so the joins are added only when returned + """ + + _requested_fields_cache = _UNSET + + def get_requested_fields(self) -> typing.Optional[typing.Set[str]]: + """The fields a read returns: ``?fields=``, else the serializer defaults. ``None`` on writes""" + if self._requested_fields_cache is _UNSET: + self._requested_fields_cache = self.__parse_requested_fields() + return self._requested_fields_cache + + def get_response_fields(self) -> typing.Optional[typing.Set[str]]: + """The fields of the response, a write answers with the read representation""" + if (_fields := self.get_requested_fields()) is not None: + return _fields + return self.__default_fields(self.get_serializer_class()) + + def get_serializer_context(self): + _context = super().get_serializer_context() + if (_fields := self.get_requested_fields()) is not None: + _context[CONTEXT_KEY] = _fields + return _context + + def setup_queryset(self, queryset): + _serializer_class = self.get_serializer_class() + if not hasattr(_serializer_class, "setup_queryset"): + return queryset + return _serializer_class.setup_queryset(queryset, self.get_response_fields(), getattr(self, "request", None)) + + def __parse_requested_fields(self) -> typing.Optional[typing.Set[str]]: + _request = getattr(self, "request", None) + if _request is None or _request.method not in READ_METHODS: + return None + + _serializer_class = self.get_serializer_class() + _raw = _request.query_params.get(FIELDS_PARAM, "") + _requested = {_name.strip() for _name in _raw.split(",") if _name.strip()} + if not hasattr(_serializer_class, "available_field_names"): + # ignoring it would silently return every field + if _requested: + raise ValidationError({FIELDS_PARAM: ["This endpoint does not support field selection."]}) + return None + if not _requested: + return self.__default_fields(_serializer_class) + + _available = _serializer_class.available_field_names() + if _unknown := sorted(_requested - _available): + raise ValidationError( + { + FIELDS_PARAM: [ + f"Unknown field(s): {', '.join(_unknown)}. Available: {', '.join(sorted(_available))}." + ] + } + ) + return _requested + + @staticmethod + def __default_fields(serializer_class) -> typing.Optional[typing.Set[str]]: + if not hasattr(serializer_class, "available_field_names"): + return None + # an explicit full set, so nested serializers still narrow to their own defaults + _default = serializer_class.default_field_names() + return _default if _default is not None else serializer_class.available_field_names() + + +class V3GenericViewSet(FieldSelectionViewSetMixin, viewsets.GenericViewSet): + """ + Base of every v3 viewset, composed with the DRF mixins it needs. + Subclasses override ``get_base_queryset``, so the ``?fields=`` setup is never skipped + """ + + # fail closed: REST_FRAMEWORK has no default, a viewset that forgets them would be AllowAny + permission_classes = [IsAuthenticated] + renderer_classes = V3_RENDERER_CLASSES + pagination_class = V3Pagination + # set here and not as DEFAULT_SCHEMA_CLASS, so drf-spectacular never inspects v2 views + schema = V3AutoSchema() + # emitted as x-stability in the schema, an endpoint is promoted by changing it + stability = "experimental" + + def get_exception_handler(self): + return problem_details_handler + + def get_base_queryset(self): + return super().get_queryset() + + def get_queryset(self): + return self.setup_queryset(self.get_base_queryset()) + + def get_read_representation(self, instance): + # refetched through get_queryset, an instance just saved has none of the annotations of setup_queryset + _instance = self.get_queryset().filter(pk=instance.pk).first() or instance + _context = self.get_serializer_context() + if (_fields := self.get_response_fields()) is not None: + _context[CONTEXT_KEY] = _fields + return self.get_serializer(_instance, context=_context).data + + +class V3CreateModelMixin(mixins.CreateModelMixin): + """Answers a create with the read representation""" + + def create(self, request, *args, **kwargs): + _serializer = self.get_serializer(data=request.data) + _serializer.is_valid(raise_exception=True) + self.perform_create(_serializer) + _data = self.get_read_representation(_serializer.instance) + return Response(_data, status=201, headers=self.get_success_headers(_data)) + + +class V3UpdateModelMixin(mixins.UpdateModelMixin): + """Answers an update with the read representation""" + + def update(self, request, *args, **kwargs): + _serializer = self.get_serializer(self.get_object(), data=request.data, partial=kwargs.pop("partial", False)) + _serializer.is_valid(raise_exception=True) + self.perform_update(_serializer) + return Response(self.get_read_representation(_serializer.instance), status=200) + + +class V3ModelViewSet( + V3CreateModelMixin, + mixins.RetrieveModelMixin, + V3UpdateModelMixin, + mixins.DestroyModelMixin, + mixins.ListModelMixin, + V3GenericViewSet, +): + pass + + +class V3RootView(APIRootView): + """The v3 root lists the endpoints only, the endpoints check their own permissions""" + + permission_classes = [AllowAny] + renderer_classes = V3_RENDERER_CLASSES diff --git a/geonode/settings.py b/geonode/settings.py index 75453296fa6..d402200caa4 100644 --- a/geonode/settings.py +++ b/geonode/settings.py @@ -435,6 +435,9 @@ "rest_framework", "rest_framework_gis", "dynamic_rest", + # OpenAPI schema for /api/v3/ only -- see geonode.api.v3.schema + "drf_spectacular", + "drf_spectacular_sidecar", # Theme "django_select2", "django_forms_bootstrap", @@ -496,9 +499,37 @@ "DEFAULT_PARENT_LOOKUP_KWARG_NAME_PREFIX": "", } +# OpenAPI schema, /api/v3/ only -- see geonode.api.v3.schema. +# +# REST_FRAMEWORK above deliberately has no DEFAULT_SCHEMA_CLASS; setting one +# globally would apply it outside v3 too. +SPECTACULAR_SETTINGS = { + "TITLE": "GeoNode API v3", + "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." + ), + "VERSION": "3.0.0", + "SCHEMA_PATH_PREFIX": "/api/v3", + "SERVE_INCLUDE_SCHEMA": False, + "PREPROCESSING_HOOKS": ["geonode.api.v3.schema.exclude_non_v3_endpoints"], + "COMPONENT_SPLIT_REQUEST": True, + # with ?fields= no response field is guaranteed, read-only fields must not be marked as required + "COMPONENT_NO_READ_ONLY_REQUIRED": True, + # the schema is the public contract and lists every v3 endpoint, also the admin-only ones + "SERVE_PERMISSIONS": ["rest_framework.permissions.AllowAny"], + # swagger and redoc served from static files, not from a CDN: offline and strict CSP deployments work + "SWAGGER_UI_DIST": "SIDECAR", + "SWAGGER_UI_FAVICON_HREF": "SIDECAR", + "REDOC_DIST": "SIDECAR", +} + REST_API_DEFAULT_PAGE = os.getenv("REST_API_DEFAULT_PAGE", 1) REST_API_DEFAULT_PAGE_SIZE = os.getenv("REST_API_DEFAULT_PAGE_SIZE", 10) REST_API_DEFAULT_PAGE_QUERY_PARAM = os.getenv("REST_API_DEFAULT_PAGE_QUERY_PARAM", "page_size") +# upper bound of page_size on API v3, a bigger value is clamped +REST_API_V3_MAX_PAGE_SIZE = int(os.getenv("REST_API_V3_MAX_PAGE_SIZE", 200)) REST_API_PRESETS = { "bare": {"exclude[]": ["*"], "include[]": ["pk", "title"]}, diff --git a/geonode/urls.py b/geonode/urls.py index 3aba40b3cb9..4648772315c 100644 --- a/geonode/urls.py +++ b/geonode/urls.py @@ -132,6 +132,8 @@ re_path(r"^api/v2/facets", include("geonode.facets.urls")), re_path(r"^api/v2/", include("geonode.assets.urls")), re_path(r"^api/v2/metadata/", include("geonode.metadata.api.urls")), + # API v3 -- single explicit include; all v3 routes live in geonode.api.v3.urls + re_path(r"^api/v3/", include("geonode.api.v3.urls")), re_path(r"", include(api.urls)), re_path( r"uploads/upload", diff --git a/pyproject.toml b/pyproject.toml index dd934a65963..062e3c602a2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -89,6 +89,8 @@ dependencies = [ "djangorestframework==3.18.3", "djangorestframework-gis==1.3.0", "drf-extensions==0.7.1", + "drf-spectacular==0.30.0", + "drf-spectacular-sidecar==2026.10.1", "geonode-dynamic-rest==2.3.0.3", "geonode-pinax-notifications==6.0.0.4",