Skip to content

Design API v3 #14540

Open
0 of 3 issues completed
Open

Description

@etj

Why

v2 has two problems a patch can't fix without breaking existing clients:

  • It's built on django-dynamic-rest, whose automatic joins and sideloading (include[]/filter{}) are hard to predict from the serializer alone, and page size is uncapped.
  • It has no OpenAPI schema, so nothing documents an endpoint automatically.

What

v3 is a clean break, not a v2 migration. Decisions made:

  • Plain DRF — ModelSerializer + explicit select_related/prefetch_related, no dynamic-rest.
  • A single ?fields= parameter replaces DREST's include[]/exclude[]/ filter{}/sort[], and prunes the query as well as the response.
  • Trailing slash is required on every v3 path — one canonical URL per endpoint.
  • Every v3 viewset must declare permission_classes explicitly; REST_FRAMEWORK has no project-wide default, so an omission means world-writable.
  • OpenAPI via drf-spectacular, scoped to v3 only. It was dropped from GeoNode entirely once before because it conflicted with dynamic-rest; safe to bring back now that v3 doesn't use it.
  • File layout follows v2's own per-app convention, one version segment deeper: shared infrastructure at geonode/api/v3/, each resource under its owning app's api/v3/. v2 itself is not touched or renamed.

Sub-issues

Sub-issues

0 of 3 Issues completed
Loading 3 sub-issues

Activity

  1. self-assigned this
    on Aug 20, 2026
  2. added theissue type on Aug 20, 2026
  3. added this to the 5.2.0 milestone on Aug 20, 2026
  4. etj commented on Aug 20, 2026

    @etj
    ContributorAuthor

    Implementation notes

    • ?fields= must prune the query, not just the response. Filtering the serializer's output alone is cosmetic -- the performance goal only lands if unrequested fields also skip their select_related/prefetch_related. Drive both from one place per resource (e.g. a field -> {select, prefetch} map), not two.
    • Trailing slash required is DRF's own default, not an invented rule -- DefaultRouter(trailing_slash=True). v2 is inconsistent (optional on the shared DynamicRouter, required on harvesting/management-command routers); v3 picks one and sticks to it.
    • drf-spectacular has failed here before. It was dropped from GeoNode entirely in redoc is broken #14201/[Fixes #14201] Dropped spectacular, replaced with docstrings for API endpoints #14202 because /api/v2/schema/redoc/ crashed -- the generator walks every registered endpoint and asserts each view carries a spectacular AutoSchema; v2's dynamic-rest viewsets didn't. Don't set DEFAULT_SCHEMA_CLASS globally in REST_FRAMEWORK -- that's exactly what caused it. Scope it per-viewset (only v3 viewsets carry the schema class) and filter v2 out via a PREPROCESSING_HOOK, so the generator never inspects a v2 view. Also exclude the schema-serving views themselves (/api/v3/schema/*) from that same hook -- they live under /api/v3/ but don't carry a spectacular schema either, so leaving them in reproduces the identical crash against spectacular's own view.
    • File layout, not yet done: shared v3 infra should live at geonode/api/v3/, each resource under its owning app (geonode/groups/api/v3/, geonode/services/api/v3/), one version segment deeper than v2's existing per-app convention.
      v2 itself does not move. We looked at retro-versioning v2 into <app>/api/v2/ for symmetry and rejected it: HTTP routes wouldn't change, but geonode_mapstore_client imports geonode.api.urls.router directly and depends on getting the same object back, so that import would break -- and we don't control every downstream package that subclasses v2 API classes by direct import (the GeoNode Project Template pattern encourages exactly that). Not worth the blast radius for cosmetic symmetry.
    • We considered bare function-based views for less framework ceremony; kept class-based ModelViewSet because moving all the way to bare functions would quietly reinvent hand-rolled pagination, validation, and (worse) the automatic fetch-then-check-object-permission ordering that GenericAPIView.get_object() gives for free. @api_view function views remain a reasonable middle ground for anything more RPC-shaped than CRUD later.
    • One more thing on the spectacular guards: they're deliberately redundant. No global DEFAULT_SCHEMA_CLASS would prevent the [Fixes #14201] Dropped spectacular, replaced with docstrings for API endpoints #14202 failure on its own; the PREPROCESSING_HOOK would too. Doing both means neither is load-bearing alone -- if a future change weakens one, the other still holds.
  5. cesarbenjamindotnet commented on Oct 7, 2026

    @cesarbenjamindotnet

    The statement:

    “Every v3 viewset must declare permission_classes explicitly; REST_FRAMEWORK has no project-wide default, so an omission means world-writable.”

    is incorrect and should be corrected, particularly because it makes a fairly strong security claim based on a misunderstanding of Django REST Framework's permission configuration.

    DRF explicitly supports a project-wide default permission policy through the DEFAULT_PERMISSION_CLASSES setting:

    REST_FRAMEWORK = {
        "DEFAULT_PERMISSION_CLASSES": [
            "rest_framework.permissions.IsAuthenticated",
        ],
    }

    The official DRF documentation states:

    “The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting.”

    See the official documentation:

    The settings documentation also explicitly says that these API policy settings are applied to every APIView-based view. ViewSets are part of DRF's APIView-based view infrastructure and use the same permission machinery.

    Therefore, a ViewSet does not need to declare permission_classes explicitly in order to be protected. If it does not override the setting locally, it uses the configured global DEFAULT_PERMISSION_CLASSES.

    There is an important distinction here:

    If the project does not configure DEFAULT_PERMISSION_CLASSES, DRF's own default is:

    [
        "rest_framework.permissions.AllowAny",
    ]

    In that specific situation, an endpoint without an explicit permission policy will indeed allow unrestricted access.

    But that is very different from claiming that "REST_FRAMEWORK has no project-wide default."

    In fact, configuring a restrictive global default such as IsAuthenticated and explicitly marking only intentionally public endpoints with AllowAny is a perfectly valid — and arguably safer — design because it provides fail-closed behavior when a developer forgets to specify permissions on a new ViewSet.

    So before requiring every v3 ViewSet to duplicate permission_classes, we should first check the project's REST_FRAMEWORK["DEFAULT_PERMISSION_CLASSES"] configuration.

    If it is already restrictive, requiring an explicit declaration on every ViewSet is a project convention or linting decision, not a DRF security requirement, and it should be documented as such rather than justified by the incorrect claim that DRF has no project-wide permission default.

  6. etj commented on Oct 29, 2026

    @etj
    ContributorAuthor

    A further idea: plugin discovery for v3 endpoints

    Why

    External apps (geonode-rndt, geonode-csw-services, project apps, ...) can't add v2 endpoints in any supported way.
    Since #14552 core apps include their URLs in geonode/urls.py, but core doesn't know about apps outside GeoNode.
    Those apps are left with two options, both fragile:

    • the project's urls.py includes them by hand, so every install has to remember it;
    • they inject into geonode.urls.urlpatterns from AppConfig.ready(), so they depend on import order. Registering
      on the shared router can also miss the cached router.urls, the bug Fragile /api/v2/ router URL registration #14552 fixed.

    v3 already puts each resource under its own app's api/v3/ package. That makes discovery cheap, and core apps and
    plugins can use the same code path.

    What

    • Discovery: geonode/api/v3/urls.py goes through apps.get_app_configs() and adds a plain include() for each
      app that has an <app>.api.v3.urls module. It runs in the URLconf, not in ready(), and core apps are found the
      same way, so no URL list has to be maintained by hand.
    • Order: apps are included in INSTALLED_APPS order, so the order no longer depends on import side effects.
    • No shared router: each app builds its own router in its own api/v3/urls.py, so no router.urls is cached
      across apps and the Fragile /api/v2/ router URL registration #14552 failure can't come back.
    • Opt-out: an API_V3_EXCLUDE_APPS setting, for apps that ship v3 modules the site doesn't want to expose.

    Sketch:

    # geonode/api/v3/urls.py
    from importlib.util import find_spec
    
    from django.apps import apps
    from django.conf import settings
    from django.urls import include, path
    
    
    def _v3_urls(app):
        name = f"{app.name}.api.v3.urls"
        try:
            found = find_spec(name) is not None
        except ModuleNotFoundError as e:
            if not name.startswith(f"{e.name}."):
                raise  # a real import error inside the app's api package
            found = False
        return name if found else None
    
    
    excluded = set(getattr(settings, "API_V3_EXCLUDE_APPS", ()))
    urlpatterns = [  # shared v3 infra (schema, ...) first
        ...
    ] + [
        path("", include(module))
        for app in apps.get_app_configs()
        if app.name not in excluded and (module := _v3_urls(app))
    ]

    Rules for plugin endpoints

    • Schema: the spectacular guards described above rely on every view under /api/v3/ carrying the spectacular
      AutoSchema. Core can't enforce that on code it doesn't ship, and a plugin viewset without it reproduces [Fixes #14201] Dropped spectacular, replaced with docstrings for API endpoints #14202.
      So core should provide a v3 base viewset that sets the schema class, and plugins are expected to subclass it. As
      a second guard, the PREPROCESSING_HOOK should also drop any view that doesn't carry the schema class, instead of
      only filtering by path.
    • Permissions: this ties in with @cesarbenjamindotnet's comment. Core can review its own viewsets for a missing
      permission_classes, but not plugin code. A restrictive DEFAULT_PERMISSION_CLASSES makes a plugin viewset that
      forgets them fail closed. Requiring explicit permission_classes then stays as a project convention on top of
      that safe default, not as the only protection.
    • Prefix clashes: two apps registering the same prefix should be an error, raised by a system check at startup,
      not "first match wins". Plugins can add v3 endpoints but not silently replace core ones.

    Out of scope

    Non-API URLs. For example, geonode-rndt replaces catalogue/csw, and that needs a defined point in
    geonode/urls.py before or after the core routes. That deserves its own issue: v3 endpoints should be added
    alongside core ones, never in place of them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions