django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

`@api_view` decorator does not provide access to all classes

Open qqii opened this issue 6 months ago • 3 comments

It does not support content_negotiation_class, metadata_class and versioning_class.

qqii avatar Jun 05 '25 12:06 qqii

Good point. What is your use case you encountered they were lacking?

At first glance, it feels borderline a new feature and there is an easy workaround (use a class based view), so I didn't think we'll implement it.

However, upon closer inspection, the default API settings (DEFAULT_CONTENT_NEGOTIATION_CLASS, DEFAULT_METADATA_CLASS, and DEFAULT_VERSIONING_CLASS) aren't honored for @api_view function based views:

https://github.com/encode/django-rest-framework/blob/74689b1f44fd3d5fd3f220b6f1e2bae650eba3d8/rest_framework/decorators.py#L58-L74

Reference:

  • When metadata_class was added: https://github.com/encode/django-rest-framework/commit/f4b1dcb167be0bbdaae2cc2a92f651536896dc16
  • When versioning_class was added: https://github.com/encode/django-rest-framework/commit/6e51e4f5cdec4f4580360a487d7bf5ebdef08709

browniebroke avatar Jun 05 '25 13:06 browniebroke

The big one for me is versioning_class, which we find DRF's numerous options very welcome.

Yes, I also discovered that it didn't respect the override either so my existing workaround is to define the decorator

def versioning_class(versioning_class):
    def decorator(func):
        func.versioning_class = versioning_class
        return func
    return decorator

and an inlined version of api_view that supports it

def api_view(http_method_names=None):
    # ...
    def decorator(func):
        # ...
        WrappedAPIView.versioning_class = getattr(func, "versioning_class", APIView.versioning_class)
        # ...
    # ...

Would you consider this out of scope for a contribution?

qqii avatar Jun 05 '25 16:06 qqii

Any thoughts @browniebroke, would you be against me opening a PR based on my branch?

qqii avatar Jun 11 '25 18:06 qqii

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Oct 18 '25 11:10 stale[bot]