[Django]-Django drf-spectacular How to split api descriptions for public and private use?

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👍

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"], ...)

Leave a comment