Reputation: 3311
I am migrating my Django 1.11.7 to 2.x. One of the problems is django-rest-swagger, it is now deprecated. And drf-yasg should now be the way for the API documentation and creation. I need to do it in a similar way of creating custom api as so it doesnt break anything in the mobile.
Previously, it looks like this (django-rest-swagger==2.1.1)
here is the old code snippet that works nicely in Django 1.11.7 and django-rest-swagger==2.1.1:
using swagger_schema.py
https://gist.github.com/axilaris/2f72fef8f30c56d5befe9e31cd76eb50
in url.py:
from rest_framework_swagger.views import get_swagger_view
from myapp.swagger_schema import SwaggerSchemaView
urlpatterns = [
url(r'^swaggerdoc/', SwaggerSchemaView.as_view()),
url(r'^api/v1/general/get_countries$', api.get_countries, name='get_countries'),
in api.py:
@api_view(['POST'])
def get_countries(request):
# ----- YAML below for Swagger -----
"""
description: countries list
parameters:
- name: token
type: string
required: true
location: form
"""
......
return Response(countries_list, status=status.HTTP_200_OK)
My question is how to do it in drf-yasg similarly, as I want to migrate this code and dont break anything on the mobile.
probably try to do this on this latest stable releases:
djangorestframework==3.9
drf-yasg==1.16.1
Upvotes: 5
Views: 4139
Reputation: 2568
You can do it like this in your api.py
. This will generate exactly what you show in the screenshot:
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import api_view, parser_classes
from rest_framework.parsers import FormParser
token = openapi.Parameter('token', openapi.IN_FORM, type=openapi.TYPE_STRING, required=True)
@swagger_auto_schema(
method="post",
manual_parameters=[token]
)
@api_view(["POST"])
@parser_classes([FormParser])
def get_countries(request):
"""
Countries list
"""
......
return Response(countries_list, status=status.HTTP_200_OK)
Note that I added @parser_classes([FormParser])
decorator to make sure the view accepts form data. You can remove it if all your endpoints work only with form data and you set it globally in DRF settings.
Here's more documentation on @swagger_auto_schema decorator.
Upvotes: 13