How to document function-based views parameters?

2019-07-23 22:04发布

I'm developing a REST API with Django 1.11 and Django REST Framework 3.7. I installed Django REST Swagger 2.1 to generate the documentation.

I'm using a function-based view like this:

from rest_framework.decorators import api_view, permission_classes

@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def jwt_auth(request, provider, format=None):
    """
    View description here
    """
    pass

Generated documentation by Swagger

As you can see, my view is recognized by Swagger and it has the correct description: "View description here".

However:

  • You can see the "Description" column is empty for the provider URL parameter.
  • The POST parameters are not documented (obviously, because there is no way for Swagger to know them)

How can I write documentation for the URL and POST parameters of a function-based view, as well as the responses?

I tried YAML Docstrings but it seems it's for the old version (0.3.x) and it doesn't work with version 2.x.

2条回答
太酷不给撩
2楼-- · 2019-07-23 22:27

Following this github issue, it seems it's not possible for the method-based views as you stated.

But I think this link can help you.

查看更多
别忘想泡老子
3楼-- · 2019-07-23 22:30

You can use Schema of DjangoRestFrameWork. http://www.django-rest-framework.org/api-guide/schemas/

In your case, you can try the following.


from rest_framework.decorators import api_view, permission_classes, schema
@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
@schema(custom_schema)
def jwt_auth(request, provider, format=None):
    """
    View description here
    """
    pass

custom schema defintion

import coreapi, coreschema
from rest_framework.schemas import AutoSchema, ManualSchema
custom_schema = AutoSchema(manual_fields=[
    coreapi.Field("username", required=True, location="form", type="string", description="username here"),
    coreapi.Field("password", required=True, location="form", type="string", description="password field"
]

Should do the trick. For more detailed info, visit the link I provided at the top. Basic POST and GET parameters should work in this way.

查看更多
登录 后发表回答