So, I have a function-based view on a DRF application that looks something like this:
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework import status
def passcode_generator(callsign: str) -> int:
return 0 # Placeholder
@api_view(["POST"])
@permission_classes([AllowAny])
def get_passcode(request):
callsign = request.data.get("callsign", None)
if callsign is None:
raise Response(
{"error": "Missing callsign"}, status=status.HTTP_400_BAD_REQUEST
)
return Response({"passcode": passcode_generator(callsign)})
Clearly, "callsign"
is the only expected argument, and it is mandatory. And that "passcode"
is the only field in the response. But DRF doesn't know that.
This means that DRF's web-browsable API page can't show the HTML form tab, and means that documentation generators can't properly document it:
So the question is, how can one document this function-based view?
Thanks!
CodePudding user response:
I'm not sure this could be done with vanilla DRF. The best schema generator for Django being supported now, as far as I know, is drf-spectacular
. So if you are using drf-spectacular
, you have to document it this way:
@extend_schema(
parameters=[
OpenApiParameter(name='callsign', description='<description>',
required=True, type=str),
],
description='More descriptive text'
)
def get_passcode(request):
callsign = request.data.get("callsign", None)
# ...
Response could be documented this way, according to tests:
@extend_schema_view(
create=extend_schema(description='creation description', responses={
201: OpenApiResponse(response=int, description='creation with int response.'),
222: OpenApiResponse(description='creation with no response.'),
223: None,
224: int,
}),
list=extend_schema(responses=OpenApiResponse(
response=OpenApiTypes.INT,
description='a list that actually returns numbers',
examples=[OpenApiExample('One', 1), OpenApiExample('Two', 2)],
)),
)