10

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.

3
  • Did you find a solution? Commented Jul 16, 2018 at 20:55
  • I didn't. I just ended up building out custom documentation on my own. Commented Jul 16, 2018 at 22:22
  • Ah, thanks. Custom documentation as in completely separate documentation or just this part using coreapi/schema in DRF? Commented Jul 18, 2018 at 8:45

1 Answer 1

7

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):
        ...
Sign up to request clarification or add additional context in comments.

4 Comments

How do you do this for built in views like list, get, etc.. ?
You can re-define them, decorate them, and return exactly what they would with super()
Thats the thing, you cant decorate them with action ... seems to be limiting. Do you have an example to share?
Oh, I see your point. No sorry, I don't have any other ideas right now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.