Django REST框架Swagger 2.0

时间:2022-01-11 03:32:05

Having a hard time configuring Swagger UI Here are the very explanatory docs: https://django-rest-swagger.readthedocs.io/en/latest/

很难配置Swagger UI以下是非常简洁的文档:https://django-rest-swagger.readthedocs.io/en/latest/

YAML docstrings are deprecated. Does somebody know how to configure Swagger UI from within the python code? or what file should I change to group api endpoints, to add comments to each endpoint, to add query parameter fields in Swagger UI?

YAML文档字符串已弃用。有人知道如何从python代码中配置Swagger UI吗?或者我应该将哪个文件更改为分组api端点,为每个端点添加注释,以在Swagger UI中添加查询参数字段?

4 个解决方案

#1


8  

This is how I managed to do it:

这就是我设法做到的方式:

base urls.py

base urls.py

urlpatterns = [
...
url(r'^api/', include('api.urls', namespace='api')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
...
]

api.urls.py

api.urls.py

urlpatterns = [
url(r'^$', schema_view, name='swagger'),
url(r'^article/(?P<pk>[0-9]+)/$', 
    ArticleDetailApiView.as_view(actions={'get': 'get_article_by_id'}), 
    name='article_detail_id'),
url(r'^article/(?P<name>.+)/(?P<pk>[0-9]+)/$', 
    ArticleDetailApiView.as_view(actions={'get': 'get_article'}), 
    name='article_detail'),
]

api.views.py. In MyOpenAPIRenderer I update the data dict to add description, query fields and to update type or required features.

api.views.py。在MyOpenAPIRenderer中,我更新数据字典以添加描述,查询字段以及更新类型或所需功能。

class MyOpenAPIRenderer(OpenAPIRenderer):
    def add_customizations(self, data):
        super(MyOpenAPIRenderer, self).add_customizations(data)
        data['paths']['/article/{name}/{pk}/']['get'].update(
            {'description': 'Some **description**',
             'parameters': [{'description': 'Add some description',
                             'in': 'path',
                             'name': 'pk',
                             'required': True,
                             'type': 'integer'},
                            {'description': 'Add some description',
                             'in': 'path',
                             'name': 'name',
                             'required': True,
                             'type': 'string'},
                            {'description': 'Add some description',
                             'in': 'query',
                             'name': 'a_query_param',
                             'required': True,
                             'type': 'boolean'},
                            ]
             })
        # data['paths']['/article/{pk}/']['get'].update({...})
        data['basePath'] = '/api'  

@api_view()
@renderer_classes([MyOpenAPIRenderer, SwaggerUIRenderer])
def schema_view(request):
    generator = SchemaGenerator(title='A title', urlconf='api.urls')
    schema = generator.get_schema(request=request)
    return Response(schema)


class ArticleDetailApiView(ViewSet):

    @detail_route(renderer_classes=(StaticHTMLRenderer,))
    def get_article_by_id(self, request, pk):
        pass

    @detail_route(renderer_classes=(StaticHTMLRenderer,))
    def get_article(self, request, name, pk):
        pass

update for django-rest-swagger (2.0.7): replace only add_customizations with get_customizations.

更新django-rest-swagger(2.0.7):仅使用get_customizations替换add_customizations。

views.py

views.py

class MyOpenAPIRenderer(OpenAPIRenderer):
    def get_customizations(self):
        data = super(MyOpenAPIRenderer, self).get_customizations()
        data['paths'] = custom_data['paths']
        data['info'] = custom_data['info']
        data['basePath'] = custom_data['basePath']
        return data

You can read the swagger specification to create custom data.

您可以阅读swagger规范来创建自定义数据。

#2


7  

So, it seems that what happened is django-rest-frameowrk added the new SchemeGenerator, but it is half-baked and missing the ability to generate action descriptions from code docs, and have an open issue about it, due in 3.5.0.

所以,似乎发生的事情是django-rest-frameowrk添加了新的SchemeGenerator,但它是半生不熟的,并且缺乏从代码文档生成动作描述的能力,并且在3.5.0中有一个关于它的公开问题。

In the meanwhile, django-rest-swagger went ahead and updated their code to work with the new SchemaGenerator, which makes it a breaking change for now.

与此同时,django-rest-swagger继续更新他们的代码以使用新的SchemaGenerator,这使它成为现在的一个重大变化。

Very weird series of events led to this ): hoping this will be resolved soon. for now, the proposed answer is the only option.

非常奇怪的一系列事件导致了这一点):希望很快就能解决这个问题。目前,建议的答案是唯一的选择。

#3


7  

Since I couldn't find any viable option here I simply created my own SchemaGenerator, like this:

由于我在这里找不到任何可行的选项,我只是创建了自己的SchemaGenerator,如下所示:

from rest_framework.schemas import SchemaGenerator


class MySchemaGenerator(SchemaGenerator):   
    title = 'REST API Index'

    def get_link(self, path, method, view):
        link = super(MySchemaGenerator, self).get_link(path, method, view)
        link._fields += self.get_core_fields(view)
        return link

    def get_core_fields(self, view):
        return getattr(view, 'coreapi_fields', ())

Created the swagger view:

创造了一个昂首阔步的观点:

from rest_framework.permissions import AllowAny
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_swagger import renderers


class SwaggerSchemaView(APIView):
    _ignore_model_permissions = True
    exclude_from_schema = True
    permission_classes = [AllowAny]
    renderer_classes = [
        CoreJSONRenderer,
        renderers.OpenAPIRenderer,
        renderers.SwaggerUIRenderer
    ]

    def get(self, request):
        generator = MySchemaGenerator()
        schema = generator.get_schema(request=request)

        return Response(schema)

Use this view in urls.py:

在urls.py中使用此视图:

url(r'^docs/$', SwaggerSchemaView.as_view()),

Add a custom field within an APIView:

在APIView中添加自定义字段:

class EmailValidator(APIView):
    coreapi_fields = (
        coreapi.Field(
            name='email',
            location='query',
            required=True,
            description='Email Address to be validated',
            type='string'
        ),
    )

    def get(self, request):
        return Response('something')

#4


0  

Using the proposed solution is a bit hacky but works fine, one may face few issues implementing the proposed solution but this doc explains django rest swagger 2 integration as well as the issues faced step by step: Django Rest Swagger 2 comprehensive documentation

使用建议的解决方案有点hacky但工作正常,实现提议的解决方案可能面临一些问题但是这个文档解释了django rest swagger 2集成以及逐步面临的问题:Django Rest Swagger 2综合文档

Much late but it may help someone looking for help now.

很晚,但它可能有助于现在寻求帮助的人。

#1


8  

This is how I managed to do it:

这就是我设法做到的方式:

base urls.py

base urls.py

urlpatterns = [
...
url(r'^api/', include('api.urls', namespace='api')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
...
]

api.urls.py

api.urls.py

urlpatterns = [
url(r'^$', schema_view, name='swagger'),
url(r'^article/(?P<pk>[0-9]+)/$', 
    ArticleDetailApiView.as_view(actions={'get': 'get_article_by_id'}), 
    name='article_detail_id'),
url(r'^article/(?P<name>.+)/(?P<pk>[0-9]+)/$', 
    ArticleDetailApiView.as_view(actions={'get': 'get_article'}), 
    name='article_detail'),
]

api.views.py. In MyOpenAPIRenderer I update the data dict to add description, query fields and to update type or required features.

api.views.py。在MyOpenAPIRenderer中,我更新数据字典以添加描述,查询字段以及更新类型或所需功能。

class MyOpenAPIRenderer(OpenAPIRenderer):
    def add_customizations(self, data):
        super(MyOpenAPIRenderer, self).add_customizations(data)
        data['paths']['/article/{name}/{pk}/']['get'].update(
            {'description': 'Some **description**',
             'parameters': [{'description': 'Add some description',
                             'in': 'path',
                             'name': 'pk',
                             'required': True,
                             'type': 'integer'},
                            {'description': 'Add some description',
                             'in': 'path',
                             'name': 'name',
                             'required': True,
                             'type': 'string'},
                            {'description': 'Add some description',
                             'in': 'query',
                             'name': 'a_query_param',
                             'required': True,
                             'type': 'boolean'},
                            ]
             })
        # data['paths']['/article/{pk}/']['get'].update({...})
        data['basePath'] = '/api'  

@api_view()
@renderer_classes([MyOpenAPIRenderer, SwaggerUIRenderer])
def schema_view(request):
    generator = SchemaGenerator(title='A title', urlconf='api.urls')
    schema = generator.get_schema(request=request)
    return Response(schema)


class ArticleDetailApiView(ViewSet):

    @detail_route(renderer_classes=(StaticHTMLRenderer,))
    def get_article_by_id(self, request, pk):
        pass

    @detail_route(renderer_classes=(StaticHTMLRenderer,))
    def get_article(self, request, name, pk):
        pass

update for django-rest-swagger (2.0.7): replace only add_customizations with get_customizations.

更新django-rest-swagger(2.0.7):仅使用get_customizations替换add_customizations。

views.py

views.py

class MyOpenAPIRenderer(OpenAPIRenderer):
    def get_customizations(self):
        data = super(MyOpenAPIRenderer, self).get_customizations()
        data['paths'] = custom_data['paths']
        data['info'] = custom_data['info']
        data['basePath'] = custom_data['basePath']
        return data

You can read the swagger specification to create custom data.

您可以阅读swagger规范来创建自定义数据。

#2


7  

So, it seems that what happened is django-rest-frameowrk added the new SchemeGenerator, but it is half-baked and missing the ability to generate action descriptions from code docs, and have an open issue about it, due in 3.5.0.

所以,似乎发生的事情是django-rest-frameowrk添加了新的SchemeGenerator,但它是半生不熟的,并且缺乏从代码文档生成动作描述的能力,并且在3.5.0中有一个关于它的公开问题。

In the meanwhile, django-rest-swagger went ahead and updated their code to work with the new SchemaGenerator, which makes it a breaking change for now.

与此同时,django-rest-swagger继续更新他们的代码以使用新的SchemaGenerator,这使它成为现在的一个重大变化。

Very weird series of events led to this ): hoping this will be resolved soon. for now, the proposed answer is the only option.

非常奇怪的一系列事件导致了这一点):希望很快就能解决这个问题。目前,建议的答案是唯一的选择。

#3


7  

Since I couldn't find any viable option here I simply created my own SchemaGenerator, like this:

由于我在这里找不到任何可行的选项,我只是创建了自己的SchemaGenerator,如下所示:

from rest_framework.schemas import SchemaGenerator


class MySchemaGenerator(SchemaGenerator):   
    title = 'REST API Index'

    def get_link(self, path, method, view):
        link = super(MySchemaGenerator, self).get_link(path, method, view)
        link._fields += self.get_core_fields(view)
        return link

    def get_core_fields(self, view):
        return getattr(view, 'coreapi_fields', ())

Created the swagger view:

创造了一个昂首阔步的观点:

from rest_framework.permissions import AllowAny
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_swagger import renderers


class SwaggerSchemaView(APIView):
    _ignore_model_permissions = True
    exclude_from_schema = True
    permission_classes = [AllowAny]
    renderer_classes = [
        CoreJSONRenderer,
        renderers.OpenAPIRenderer,
        renderers.SwaggerUIRenderer
    ]

    def get(self, request):
        generator = MySchemaGenerator()
        schema = generator.get_schema(request=request)

        return Response(schema)

Use this view in urls.py:

在urls.py中使用此视图:

url(r'^docs/$', SwaggerSchemaView.as_view()),

Add a custom field within an APIView:

在APIView中添加自定义字段:

class EmailValidator(APIView):
    coreapi_fields = (
        coreapi.Field(
            name='email',
            location='query',
            required=True,
            description='Email Address to be validated',
            type='string'
        ),
    )

    def get(self, request):
        return Response('something')

#4


0  

Using the proposed solution is a bit hacky but works fine, one may face few issues implementing the proposed solution but this doc explains django rest swagger 2 integration as well as the issues faced step by step: Django Rest Swagger 2 comprehensive documentation

使用建议的解决方案有点hacky但工作正常,实现提议的解决方案可能面临一些问题但是这个文档解释了django rest swagger 2集成以及逐步面临的问题:Django Rest Swagger 2综合文档

Much late but it may help someone looking for help now.

很晚,但它可能有助于现在寻求帮助的人。