Skip to content

Instantly share code, notes, and snippets.

@williln
Last active December 15, 2022 19:49
Show Gist options
  • Save williln/fd7442c790103f4fd6ab7f8365f203d0 to your computer and use it in GitHub Desktop.
Save williln/fd7442c790103f4fd6ab7f8365f203d0 to your computer and use it in GitHub Desktop.
Some drf-yasg examples
from drf_yasg import openapi
from drf_yasg.utils import no_body, swagger_auto_schema
"""
For actions, a lot of times Swagger will pick up on the serializer you pass to serializer_class in the decorator.
But when you're using different input and output serializers or doing anything fancy, Swagger doesn't like it.
Swagger also isn't great at picking up on the status you return if you're not returning a 200 or 201.
"""
class SampleView(generics.GenericAPIView):
@swagger_auto_schema(
responses={status.HTTP_204_NO_CONTENT: ""}, # You can set the statuses this returns if it's not a 200
query_serializer=SampleSpecialSerializer, #If you're expecting specific query params, this is helpful
)
def post(self, request):
pass
@swagger_auto_schema(
responses={status.HTTP_201_CREATED: SampleSerializer()}, # You can also pass a serializer to represent whatever your endpoint returns
request_body=no_body # You can set request_body to no_body if your endpoint doesn't take any params
)
@action(... )
def some_action(self, request):
pass
class MyListView(ListAPIView):
serializer_class = MyListSerializer
@swagger_auto_schema(
manual_parameters=[. # You can also set manual query params you're expecting
openapi.Parameter(
"title",
openapi.IN_QUERY,
description="Filter on title",
type=openapi.TYPE_STRING,
required=True,
)
]
)
def get(self, request, *args, **kwargs):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment