pythondjangopython-3.xdjango-rest-framework

Django Rest Framework custom schema for view in viewset


I have an API built using Django and Django REST Framework. I have a model that returns some JSON that is built that doesn't correspond to a typical Django model. So the auto-documentation feature that seems to utilize knowledge about Django models doesn't work for some of my views.

In particular, I have a viewset that returns some typical API views (like a list of objects), and some views that return some of my custom objects. I'd like to build documentation for these custom objects, but I am not sure how to override the schema for a particular endpoint within a viewset. How can I override the schema generated for a single view in a DRF viewset?

DRF seems to provide this functionality for views, but I want to do the same for Viewsets.


Solution

  • OK, after a lot of try-fail-retry, I finally got it to work - you lose some of the auto(magical) introspection, like the id path parameter and the description taken from the docstring, but I still thing it's worth it:

    custom_schema = ManualSchema(
        fields=[
            coreapi.Field(
                "id",
                required=True,
                location="path",
                schema=coreschema.String(
                    title="ID",
                    description="Foobar ID.",
                )
            ),
            coreapi.Field(
                "foobar",
                location="query",
                schema=coreschema.String(
                    title="Foobar",
                    description="Foobar?",
                )
            ),
        ],
        description="Foobar!",
    )
    
    
    class FoobarViewSet(viewsets.ReadOnlyModelViewSet):
    
        @action(methods=["get"], detail=True, schema=custom_schema)
        def foobar(self, request, id=None):
            ...