Django REST Swagger

Introduction

Swagger Django REST framework / OpenAPI documentation generator. Help us generate api documentation.

installation

pip install django-rest-swagger

The rest-framework-swaggerregistration to the app as follows:

settings.py

INSTALLED_APPS = [
    ...
    'rest_framework_swagger',
    ...
]

Note: If you are using the new version django-rest-framework, you need to add the following in your configuration, otherwise it will error:

# 错误信息
AttributeError: 'AutoSchema' object has no attribute 'get_link'
# REST framework
REST_FRAMEWORK = {
    ...
    # 新版drf schema_class默认用的是rest_framework.schemas.openapi.AutoSchema
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    ...
}

Quick

To quick start, use the get_swagger_viewshortcut. This will produce a generic set of architectural views. For more advanced usage, refer to "schemas" section.

Examples

urls.py

from django.conf.urls import url
from rest_framework_swagger.views import get_swagger_view

schema_view = get_swagger_view(title='API')  # title就是文档的名字

urlpatterns = [
    url(r'^docs/$', schema_view)
]

views.py

class Users(APIView):
    """
    get: user信息
    post: 修改user信息
    """

    def get(self, request):
        return Response({'name': 'liu'})

    def post(self, request):
        return Response({'age': 18})

Access http://127.0.0.1:8000/docs/, to the following figure:

1583031702542

Shader Architecture

Django REST Swagger contains two renderer. OpenAPIRendererAnd SwaggerUIRenderer.

OpenAPIRendererIt is responsible for generating JSON specification, SwaggerUIRendererrendering UI (HTML / JS / CSS) .

Note : To render UI, it must include two renderers. If you want to customize a user interface, OpenAPIRenderer may be used alone.

get_swagger_viewShortcut

For convenience, a shortcut is provided with a reasonable default configuration to generate documentation for your API SwaggerUI. The view has the following characteristics:

  • DRF authority to enforce class and user context. This means that if the view requires authentication, an anonymous user may not see the complete list of endpoints.
  • Anyone can view the document, however, will only generate documentation for publicly available endpoints.
  • Rendering CoreJSON

parameter:

title: Title of the document None(default: )

url: URL of the document (if not on the same host or path). It can be a relative path, or an absolute URL. (Default:None )

Advanced Usage

In order to better control the document, use architecture to create your own view based on the view the view function or class-based. If you want to generate a specific URL or URL conf mode documents, it would be useful.

More detailed documentation about the schema generator, see:

http://www.django-rest-framework.org/api-guide/schemas/

Example: based on the view class

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


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

    def get(self, request):
        generator = SchemaGenerator()
        # request参数也不是必须的,如果要将每个用户的权限应用于生成的架构,则可以使用该参数。
        schema = generator.get_schema(request=request)  

        return Response(schema)
    
# urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('user/', Users.as_view()),
    path('swagger/', SwaggerSchemaView.as_view()),  # 访问该地址同样会展示接口文档
]

Example: based on the view function

from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import response, schemas

@api_view()
@renderer_classes([SwaggerUIRenderer, OpenAPIRenderer])
def schema_view(request):
    generator = schemas.SchemaGenerator(title='Pastebin API')
    return response.Response(generator.get_schema(request=request))

Settings

Django REST Swagger Django REST framework with the same configuration. You can be configured by defining a set of SWAGGER_SETTINGS in Settings.py.

Examples

settings.py

# swagger 配置项
SWAGGER_SETTINGS = {
    # 基础样式
    'SECURITY_DEFINITIONS': {
        "basic":{
            'type': 'basic'
        }
    }, 
    # 如果需要登录才能够查看接口文档, 登录的链接使用restframework自带的.
    'LOGIN_URL': 'rest_framework:login',
    'LOGOUT_URL': 'rest_framework:logout',
    # 'DOC_EXPANSION': None,
    # 'SHOW_REQUEST_HEADERS':True,
    # 'USE_SESSION_AUTH': True,
    # 'DOC_EXPANSION': 'list',
    # 接口文档中方法列表以首字母升序排列
    'APIS_SORTER': 'alpha',
    # 如果支持json提交, 则接口文档中包含json输入框
    'JSON_EDITOR': True,
    # 方法列表字母排序
    'OPERATIONS_SORTER': 'alpha',
    'VALIDATOR_URL': None,
}

verification method

USE_SESSION_AUTH

Switch between Django Auth as the authentication mechanism. Set it Truewill display a login / logout button and csrf_tokens API to publish on Swagger UI.

default: True

Results are as follows:

1582968675099

# 将其设置为False,效果如下图
SWAGGER_SETTINGS = {
    'USE_SESSION_AUTH': False, 
}

1582968744860

Note: "login / logout" button depend on LOGIN_URLand LOGOUT_URLset to the default /accounts/login. These can SWAGGER_SETTINGSbe arranged at or Django settings.

urls.py

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

settings.py

# 方式一
LOGIN_URL = 'rest_framework:login'
LOGOUT_URL = 'rest_framework:logout'

# 方式二
SWAGGER_SETTINGS = {
    'LOGIN_URL': 'rest_framework:login',
    'LOGOUT_URL': 'rest_framework:logout',
}

LOGIN_URL

URL for the login session authentication. URL patterns to accept named.

default: django.conf.settings.LOGIN_URL

LOGOUT_URL

For the cancellation of the session authentication URL. URL patterns to accept named.

default: django.conf.settings.LOGOUT_URL

SECURITY_DEFINITIONS

Security define configuration Swagger which authentication method can be used. Currently the program type of OpenAPI 2.0 specification supported basic, apiKeyand oauth2.

For more information about the available options, consult the OpenAPI security object definitions .

default:

{
    'basic': {
        'type': 'basic'
    }
}

SwaggerUI settings

The following are SwaggerUI some basic configuration settings. Note that for more advanced use cases, you may want to write your own rest_framework_swagger/static/init.jsfile.

APIS_SORTER

To alphaenable alphabetical order.

default: None

DOC_EXPANSION

Control API list is displayed. Can be set to:

  • None: All operations have been folded
  • "list": List all operations
  • "full": Extend all operations

default: None

SWAGGER_SETTINGS = {
    ...
    'DOC_EXPANSION': 'list',
}

JSON_EDITOR

Enable graphical view for editing complex entity.

default: False

OPERATIONS_SORTER

Sort the list of actions for each API. Can be set to:

  • alpha: Sorted alphabetically
  • method: Sort by HTTP method

default: None

SHOW_REQUEST_HEADERS

To Truedisplay the request header.

default: False

SUPPORTED_SUBMIT_METHODS

You can use "Try it out!" HTTP methods to interact with the list. Button.

default: ['get', 'post', 'put', 'delete', 'patch']

VALIDATOR_URL

URL swagger.io online schema validators. It can be modified to point to the local installation, or set Noneto disable.

default: https://online.swagger.io/validator/

Custom template

template

SwaggerUIRenderer template can be used to customize by covering rest_framework_swagger/index.html.

Here are some basic areas that can be customized:

  • {% block extra_styles %} Add additional style sheets
  • {% block extra_scripts %} Add other scripts.
  • {% block user_context_message %} Custom "Hello, user" message (Django session only)
  • {% block extra_nav %} Placeholders for other content navigation bar.
  • {% block logo %} Logo area of ​​the navigation bar.

Version title

The following code assigns a version number attached to each request, which is necessary rest_framework.versioning.AcceptHeaderVersioning. It should go into rest_framework_swagger/index.htmlyour template path.

{% extends "rest_framework_swagger/base.html" %}

{% block extra_scripts %}
<script type="text/javascript">
  $(function () {
    var ApiVersionAuthorization = function () {};
    ApiVersionAuthorization.prototype.apply = function (obj) {
      obj.headers['Accept'] += '; version=1.0';
      return true;
    };
    swaggerUi.api.clientAuthorizations.add(
        'api_version',
        new ApiVersionAuthorization()
    );
  });
</script>
{% endblock extra_scripts %}

Note: After the 2.0 version of how to pass parameters, temporarily did not understand. The old version can be written directly in the string. The new version does not find a solution in the document, I would like to know who can teach the next.

Guess you like

Origin www.cnblogs.com/liuweida/p/12391900.html