3

I want to make 2 different documentations. One is for public with few api methods and no authz. Another one is for private usage with all api methods and only for authorized users.

hjortron
  • 329
  • 1
  • 13

2 Answers2

3

2 choices:

  1. If you use the build-in Swagger and the user visiting the UI is somehow auth'ed, you can use the setting 'SERVE_PUBLIC': False. It will filter the schema based on the permissions the requesting user has access to. Spectacular will attempt to use the (first) credentials provided by the Authorize button and fetch the schema with that. If your auth method differs from DRF's setting AUTHENTICATION_CLASSES, you might also need to set spectacular's SERVE_AUTHENTICATION accordingly.

  2. Or actually create 2(+2) endpoints that serve distinct schemas and potentially customize them

# public part
path('api/schema-public/', SpectacularAPIView.as_view(
    custom_settings={
        'SERVE_URLCONF': [...]  # urlpatterns with the public endpoint list
    },
), name='schema-public'),
path('api/schema/swagger-ui-public/', SpectacularSwaggerView.as_view(url_name='schema-public')),

# private part
path('api/schema-private/', SpectacularAPIView.as_view(
    # settings deviating from global spectacular settings go here.
    custom_settings={
        'TITLE': 'Private API',
        'SERVE_URLCONF': [...]  # urlpatterns with the private endpoint list
        ...
    },
    # not required but might want to also protect if it is sensitive
    authentication_classes=[...],
    permission_classes=[...],
), name='schema-private'),
path('api/schema/swagger-ui-private/', SpectacularSwaggerView.as_view(url_name='schema-private')),
Insa
  • 1,610
  • 12
  • 17
  • I receive "TypeError: SpectacularSwaggerView() received an invalid keyword 'custom_settings'. as_view only accepts arguments that are already attributes of the class." – Angwen May 10 '23 at 10:35
  • 1
    oh sry, that was a copy&paste error. the private part was correct. The `custom_settings` parameter belongs into `SpectacularAPIView` – Insa May 11 '23 at 11:24
1

In my case Insa's second choice lead to SERVE_URLCONF not allowed in custom_settings. use dedicated parameter instead. error (drf-spectacular: 0.24.0)
So I separated public_urlpatterns in separated file named public_urls.py with urlpatterns list, then created new

path(..., SpectacularAPIView.as_view(urlconf=["app_name.public_urls"], ...)
Damir Nafikov
  • 162
  • 1
  • 9