我想制作两个不同的文档。一种是面向公众的,API 方法很少,也没有授权。另一种是用于所有 api 方法的私人使用,并且仅适用于授权用户。
2个选择:
如果您使用内置 Swagger 并且访问 UI 的用户以某种方式进行了身份验证,则可以使用设置
'SERVE_PUBLIC': False
。它将根据请求用户有权访问的权限来过滤架构。 Spectacular 将尝试使用 Authorize
按钮提供的(第一个)凭据并使用该凭据获取架构。如果您的身份验证方法与 DRF 的设置AUTHENTICATION_CLASSES
不同,您可能还需要相应地设置壮观的SERVE_AUTHENTICATION
。
或者实际创建 2(+2) 个端点来服务不同的模式并可能自定义它们
# 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 的第二个选择导致
SERVE_URLCONF not allowed in custom_settings. use dedicated parameter instead.
错误(drf-spectaulous:0.24.0)public_urls.py
的单独文件中,然后创建新的
path(..., SpectacularAPIView.as_view(urlconf=["app_name.public_urls"], ...)
这是一个简单的方法来指定要在 drf 壮观的 swagger 文档中包含哪些 url:
# This path generates the OpenAPI schema for the urls specified
# in the third_party_api.urls file
path(
"api/public/",
SpectacularAPIView.as_view(urlconf=["third_party_api.urls"]),
name="public-swagger-ui", # note this name
),
# This path generates a swagger view based on a specified url_name
# which maps to the path above, where only certain url patterns are included
path(
"api/public/swagger-ui/",
SpectacularSwaggerView.as_view(
url_name="public-swagger-ui", # this is the name of the path above
),
name="swagger-ui",
),