3👍
2 choices:
-
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 theAuthorize
button and fetch the schema with that. If your auth method differs from DRF’s settingAUTHENTICATION_CLASSES
, you might also need to set spectacular’sSERVE_AUTHENTICATION
accordingly. -
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')),
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"], ...)
- [Django]-Django – Can a POST and GET request be returned in one HttpRequest?
- [Django]-Unable to override django-allauth templates