Skip to content

Add support for the HTTP QUERY method (RFC 10008) - #10091

Open
BenA-SA wants to merge 5 commits into
encode:mainfrom
BenA-SA:query-method-support
Open

BenA-SA wants to merge 5 commits into
encode:mainfrom
BenA-SA:query-method-support

Conversation

@BenA-SA

@BenA-SA BenA-SA commented Oct 30, 2026 •

Copy link
Copy Markdown

Refs discussion #10024.

Django 6.2 adds the QUERY method from RFC 10008 (django/django#21855): safe and idempotent like GET, but with a request body. It adds "query" to View.http_method_names, treats QUERY as CSRF-safe, and adds RequestFactory.query().

That already breaks DRF against Django main: two tests in tests/test_decorators.py map every name in http_method_names onto http.HTTPMethod, which has no QUERY member. This PR fixes those and adds support for QUERY on every supported Django version. On Django 6.1 and earlier it adds QUERY the same way compat.py already adds PATCH, and matches Django 6.2's CSRF handling, so QUERY behaves the same on all of them.

Size

Added Removed
Library code (rest_framework/) 85 9
Tests (tests/) 402 4
Docs (docs/) 82 8

The change to how DRF behaves is 85 lines. 32 of those add Request.filter_params. Most of the diff is tests.

Changes

  • Permissions: QUERY is added to SAFE_METHODS, matching the RFC and Django's CSRF handling. It is also added with no required permissions ('QUERY': []) to the perms_map of both DjangoModelPermissions and DjangoObjectPermissions. If a project overrides perms_map and doesn't list QUERY, those classes refuse it with 405.
  • Routers and viewsets: SimpleRouter maps QUERY to a viewset's query() on the list route only. Viewsets that don't define query() are unaffected. A viewset only answers QUERY on routes that map it, so detail routes return 405 and leave it out of Allow. An existing @action named query keeps its own route and isn't bound to the QUERY method.
  • Request.filter_params: for a QUERY request, this merges the parsed body over the URL query parameters, with the body winning when a key appears in both. For every other method it is simply query_params. SearchFilter and OrderingFilter read from it, so a QUERY list view can carry its filters in the body. Pagination parameters still come from the URL. If the body isn't a JSON object or form, filtering returns 400.
  • Django before 6.2: compat.py adds query to View.http_method_names, as it already does for patch. Without it, viewset and router query() handlers returned 405 while @api_view(["QUERY"]) worked. Thanks to @ege-arhan, who spotted this and suggested the fix; they're credited as co-author on that commit.
  • CSRF: SessionAuthentication doesn't require a CSRF token for QUERY. Django 6.2 exempts it itself; on earlier versions session-authenticated QUERY requests without a token were rejected with 403.
  • Test client: APIRequestFactory.query() and APIClient.query() accept format and content_type, like post(). MethodMapper gains .query().
  • Schemas: the deprecated OpenAPI generator skips QUERY, because OpenAPI 3.0 has no query operation.
  • Docs: views, viewsets, requests, filtering, permissions, routers, testing, schemas and the CSRF topic.

Things worth reviewing

  • SAFE_METHODS. This is the line with the most security impact. IsAuthenticatedOrReadOnly and DjangoModelPermissionsOrAnonReadOnly will now let anonymous users send QUERY to views that handle it. A QUERY handler must therefore never write, which is what the RFC requires. Django makes the same call for CSRF.
  • filter_params is the only new public API. Without it, the built-in filters ignore the body of a QUERY request. It also gives third-party filter backends one place to read QUERY parameters from, and I plan to propose using it in django-filter and django-rest-framework-datatables, so I'd prefer to keep it in this PR.
  • A viewset attribute named query. If a viewset has a non-handler attribute or helper method called query, Django 6.2 already treats it as a QUERY handler. With AllowAny that crashes upstream on every route. With this PR it is limited to the list route, but combined with DjangoModelPermissions that route now returns 500 rather than 405. Because compat.py now adds QUERY on earlier Django versions too, this applies there as well, including to plain Django views with a query attribute, as it will on 6.2.

Not included

  • Adding Django 6.2 to tox and the classifiers. I've left this for the usual PR at the RC stage, since there is no 6.2 pre-release on PyPI yet.
  • drf-spectacular support. It crashes on views that define query(), so I'll raise that with drf-spectacular separately.

Testing

Each new test was checked by reverting the line of code it covers and confirming that it fails. The QUERY tests run on every Django version.

  • Django 6.1: 1682 passed
  • Django main (6.2.dev): 1682 passed
  • pre-commit: clean

Django 6.2 adds QUERY to View.http_method_names, which already fails
two tests in tests/test_decorators.py against Django main. Support it
properly on Django 6.2 and later:

- Add QUERY to SAFE_METHODS and to the perms_map of
  DjangoModelPermissions and DjangoObjectPermissions.
- Add MethodMapper.query(), and .query() to APIRequestFactory and
  APIClient.
- Route QUERY to a viewset's query() on the list route. A viewset only
  answers QUERY where the route maps it, and an existing @action named
  query keeps its own route.
- Add Request.filter_params, which merges a QUERY request's parsed body
  over its URL query parameters, and read it from SearchFilter and
  OrderingFilter. Pagination parameters stay in the URL.
- Exclude QUERY from the deprecated OpenAPI generator, since OpenAPI
  3.0 has no query operation.
BenA-SA added a commit to BenA-SA/drf-query-method that referenced this pull request Oct 30, 2026
- patch() applies encode/django-rest-framework#10091 to DRF in place:
  routers, viewsets, SearchFilter, OrderingFilter, SAFE_METHODS and the
  Django permission maps, request.filter_params, MethodMapper.query(),
  the test factory and client, and the deprecated schema generator.
  When django-filter is installed, DjangoFilterBackend reads the body
  too. It leaves DRF alone once DRF supports QUERY itself, and unpatch()
  reverts it for tests.
- Opt-in classes with the same names as DRF's and django-filter's, for
  projects that would rather change imports than patch.
- add_query_method() lets Django before 6.2 dispatch QUERY.
- django-filter receives body values as strings, so JSON numbers and
  booleans don't reach widgets that split on commas.

Tested across Django 4.2-6.1 with DRF 3.16-3.18, Django main with DRF
main, and DRF with native QUERY support.
@ege-arhan

Copy link
Copy Markdown

QUERY is unreachable on every Django version currently supported by the project, not just on 6.2+.

APIView.dispatch() (rest_framework/views.py:517) checks request.method.lower() in self.http_method_names, and APIView inherits http_method_names from django.views.generic.View. compat.py:49-52 patches that tuple for PATCH; nothing does the same for QUERY, and upstream Django only has it from 6.2. tests/utils.py:8 hides this with requires_query_method, so the new routes and filters are skipped on 5.2, 6.0 and 6.1 instead of failing.

Repro on head c50d1ec6d99656881320048b257db655a7089220 with Django 6.1.2 (also reproduces on 5.2.18 and 6.0.9):

from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.routers import SimpleRouter

class VS(viewsets.ViewSet):
    def query(self, request):
        return Response({"params": dict(request.filter_params)})

router = SimpleRouter()
router.register("vs", VS, basename="vs")
urlpatterns = router.urls
QUERY /vs/?x=1  body {"y": 2}
→ 405 {"detail": "Method \"QUERY\" not allowed."}

api_view(["QUERY"]) works, because there http_method_names is built from the decorator argument, which makes the router/viewset path look supported when it is not.

Fix matches the existing PATCH shim in rest_framework/compat.py:

# QUERY method (RFC 10008) is not implemented by Django before 6.2
if 'query' not in View.http_method_names:
    View.http_method_names = View.http_method_names + ['query']

With that added and nothing else changed, the same request returns 200 {'params': {'x': ['1'], 'y': [2]}} on 6.1.2, and tests/test_routers.py tests/test_filters.py tests/test_permissions.py go from 150 passed, 28 skipped to 178 passed (the skips exist only because of the marker). Then requires_query_method can either be dropped or kept for cases that genuinely need Django's own handling.

@auvipy
auvipy self-requested a review November 1, 2026 11:35
BenA-SA and others added 2 commits November 1, 2026 11:46
APIView.dispatch() only routes methods listed in View.http_method_names,
which Django adds `query` to from 6.2. On earlier versions viewset and
router `query()` handlers returned 405, while `@api_view(["QUERY"])`
worked because it builds its own list. Add `query` in compat, as is
already done for PATCH, so QUERY works on every supported Django version.

The `requires_query_method` test marker is no longer needed, so the
QUERY tests now run on every supported Django version.

Co-authored-by: Ege <68082325+ege-arhan@users.noreply.github.com>
QUERY is a safe method, so it needs no CSRF token. Django's CSRF check
exempts it from 6.2 onwards, but earlier versions only exempt GET, HEAD,
OPTIONS and TRACE, so session-authenticated QUERY requests without a
token were rejected with 403. Skip the check for QUERY in
SessionAuthentication.enforce_csrf(), matching Django 6.2 on every
supported version.
@BenA-SA

BenA-SA commented Nov 1, 2026

Copy link
Copy Markdown
Author

Thanks @ege-arhan, good catch. I reproduced the 405 on 6.1 and confirmed that @api_view(["QUERY"]) works there while viewsets don't, which was misleading. I've added your compat.py change and removed the requires_query_method marker, so the QUERY tests now run on every Django version, and I've credited you as co-author on that commit.

Your change also exposed a second gap. On Django before 6.2, SessionAuthentication still required a CSRF token for QUERY (403 without one), because Django's CSRF check only exempts it from 6.2 onwards. A separate commit makes enforce_csrf() skip the check for QUERY, matching 6.2.

One side effect: the existing caveat about a viewset helper or attribute named query now applies on older Django versions too, as it will on 6.2. I've noted that in the description.

@browniebroke browniebroke left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haven't looked in detail yet, but should this be available only for Django 6.1? Should we build this on top of the APIs from django/django#21855?

I'm a bit surprised to the see that the tests pass on all versions, including the ones running against older Django versions.

Comment thread rest_framework/request.py
Comment on lines +223 to +251
def filter_params(self):
"""
The parameters that filter backends should read.

For most methods this is `request.query_params`. A `QUERY` request
(RFC 10008) carries its query in the request body, so the parsed body
is merged over the URL query parameters, with the body taking
precedence for any key present in both.
"""
if self.method != 'QUERY':
return self.query_params

body = self.data
if not isinstance(body, Mapping):
raise exceptions.ParseError(
'QUERY request body must be an object of parameters, '
'not %s.' % type(body).__name__
)

if not isinstance(body, MultiValueDict):
body = MultiValueDict({
key: value if isinstance(value, list) else [value]
for key, value in body.items()
})

params = self.query_params.copy()
for key, values in body.lists():
params.setlist(key, values)
return params

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That feels like the main thing we should pay attention to...

Comment thread rest_framework/compat.py
Comment on lines +55 to +57
# QUERY method (RFC 10008) is not implemented by Django before 6.2
if 'query' not in View.http_method_names:
View.http_method_names = View.http_method_names + ['query']

@browniebroke browniebroke Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, I see... I'm not a big fan of reaching into Django like that.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I worked on QUERY in Django and I see why you don't like it but it would also feel 'weird' to say: DRF 3.19 has QUERY but only if your Django is > 6.2; especially because DRF typically supports all current django's. But maybe it's unavoidable. It would be similarly weird if DRF would only start supporting QUERY when django 6.2 is the 'oldest supported' version....

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm happy to implement either route - I thought it made sense to try and support the new Query method as much as possible retrospectively in case there were projects that would benefit from it that would have a difficult time upgrading to Django 6.2 + DRF 3.19, hence this approach, however I appreciate your point of view too in preferring not to reach into Django. Obviously we'd need to reach into Django to support Query retrospectively, so it seems to me that it's one or the other, but I'm happy to be guided on which.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I worked on QUERY in Django

Thanks for jumping in!

it would also feel 'weird' to say: DRF 3.19 has QUERY but only if your Django is > 6.2

I don't know... Consider the opposite: if you install Django 6.0 and DRF 3.19, you would have support for the QUERY method only in DRF view, not in plain Django views, which feels a bit weird to me too.

It would be similarly weird if DRF would only start supporting QUERY when django 6.2 is the 'oldest supported' version....

Agree on this, that's definitely not an option, as it would only be in a very long time :)

TBH, I haven't made up my mind yet, it's just something I noted while browsing the diff.

I'm slightly concerned about the unintended side effects of doing this monkey patching, as I can imagine it might trip up other 3rd party Django packages. I can easily see someone else checking this for feature detecting QUERY support in Django.

On the other hand, implementing the QUERY method in DRF only if Django supports it might be itself technically challenging, that would probably add a lot of if branches to this patch.

I probably need to get up to speed with the Django patch to review this properly.

I'm happy to implement either route

Thanks for the offer. I would recommend to NOT waste time/tokens on that just yet :)

@auvipy auvipy added this to the 3.19 milestone Nov 9, 2026

This branch has not been deployed

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

Labels

None yet

Development

Successfully merging this pull request may close these issues.

5 participants