0

Using django-rest-framework, I need to create an endpoint that lists links to other endpoints.

router = DefaultRouter()
router.register(r'pepperonis', views.PepperoniViewSet, 'Pepperoni')
router.register(r'supremes', views.SupremeViewSet, 'Supreme')
router.register(r'some-unrelated-endpoint', views.UnrelatedViewSet, 'Unrelated')

These viewsets I'm interested in all inherit from the same class:

class Pizza(viewsets.ModelViewSet):
    pass

class PepperoniViewSet(Pizza):
    pass

class SupremeViewSet(Pizza):
    pass

I can get all the relevant viewsets from Pizza.__subclasses__(). How can I create an API endpoint that lists hyperlinks to only these endpoints?

I'll need the endpoint to return something like this:

[{"url": "http://example.com/api/pepperonis/"}, {"url": "http://example.com/api/supremes/"}
Jon
  • 451
  • 1
  • 7
  • 19

2 Answers2

0

You can use HyperlinkedRelatedField in your Serializer to do this.

Example:

class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.HyperlinkedRelatedField(
    many=True,
    read_only=True,
    view_name='track-detail'
)

class Meta:
    model = Album
    fields = ('album_name', 'artist', 'tracks')

It will give result like:

{
'album_name': 'Graceland',
'artist': 'Paul Simon',
'tracks': [
    'http://www.example.com/api/tracks/45/',
    'http://www.example.com/api/tracks/46/',
    'http://www.example.com/api/tracks/47/',
    ...
]
}

References:

django-rest-framework HyperLinkRelatedField Documentation.

Piyush Maurya
  • 1,945
  • 16
  • 26
-1

Do you want this endpoint to be at the base of our API? If so, (I could be wrong), but I believe the default router will automatically create an endpoint at the root of your API that links to all your other endpoints.

MrName
  • 2,363
  • 17
  • 31
  • The endpoint will need to be explicit. I have flexibility with where I put the endpoint, but I'll need to also include things like the model's verbose name. – Jon Aug 19 '17 at 23:13