'How to access Wagtail Routable page routes in Django REST framework?

I have got a Wagtail routable page with a bunch of routes defined:

class MyRoutable(RoutablePageMixin,...):
  # stuff
  
  @route(<regex to represent /<album_id>-<album_title_slug>/<song_title_slug>/)
  def do_something_with_song_data(self):
    # do something with song data
    return SomeResponse
  
  # more routes

In Django REST framework, I am able to get the Wagtail pages with something like:

/api/v2/pages/<wagtail_page_id>/

What would the url look like for accessing such routes defined in a Wagtail routable page? I am looking for the proper way of getting:

/api/v2/pages/.../006-red-pill-blues/girls-like-you/


Solution 1:[1]

You can't do this with Django REST Framework. Django REST Framework only knows about the data that exists on the Page object itself - in other words, the set of fields you edit in the admin interface. When you write a @route method, you're doing some additional data lookups, but immediately returning the results as an HTML page, so there's no way for Django REST Framework to have access to that raw data.

A couple of alternative approaches:

  • Presumably your song data is stored in Song / Album models? If so, define a Django REST Framework endpoint for those models, not the page model.
  • Create additional routes on the routable page, perhaps with a URL like /<album_id>-<album_title_slug>/<song_title_slug>.json, that return a JsonResponse object. That way, you can return the same kind of data that you'd get from DRF, without using DRF itself.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gasman