简体   繁体   中英

DRF: How to add authentication and permissions info from class-based views into autogenerated documentation?

In Django Rest Framework you can simply generate documentation:

https://www.django-rest-framework.org/topics/documenting-your-api/#documenting-your-api

from rest_framework.documentation import include_docs_urls

urlpatterns = [
    ...
    url(r'^docs/', include_docs_urls(title='My API title'))
]

Autogenerated documentation has request body nicely generated from serializer, nice documentation from docs but how to add authentication and permission classes information?

Some of my class-based views have custom authentication_classes and permission_classes and how to display information about them?

Look into include_docs_urls will see this:

def include_docs_urls(
        title=None, description=None, schema_url=None, public=True,
        patterns=None, generator_class=SchemaGenerator,
        authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
        permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES,
        renderer_classes=None):
    ....

So, the solution is:

Setup the authentication_classes & permission_classes in settings.py

  • Sample authentication_classes:
# settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',  # <---- 1
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'common.permissions.IsDeveloper',   # <---- 2 don't forget the ','
    )
}

Note:
1. SessionAuthentication is needed because DRF Self describing APIs use session to keep user login
2. common.permissions.IsDeveloper is a custom permission class you can define your self and put the reference location as a string here, you can use default permission too.

  • Sample permission class:
# common/permissions.py

class IsDeveloper(permissions.BasePermission):
    def has_permission(self, request, view):
        user_groups = request.user.groups.values_list('name', flat=True)
        return bool('Developer' in user_groups)

Then if you didn't login or login user not in 'Developer' Group, will come to:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM