How to Pass a Request Object from Wagtail API to a Page
,Introduction
When using Wagtail's API to fetch website pages, the APIField class allows you to add custom fields. But what if you also need to incorporate the request object into your custom field?
Why the Request Object is Important
I ran into this issue because I wanted to fetch the fully-rendered HTML of a page via the Wagtail API, eliminating the need to manually render the StreamField in my Vue.js blog theme.
Code Example
To achieve this, use the APIField class as demonstrated in the code snippet below:
from wagtail.models import Page
from wagtail.api import APIField
from rest_framework.fields import Field
class HtmlField(Field):
def to_representation(self, page):
return page.serve(self.context["request"])
class Post(Page):
...
api_fields = [
APIField("html", serializer=HtmlField(source="*")),
]
Understanding the source="*" Parameter
The `source="*"` parameter is special: it enables the `to_representation` method to work with the entire page object, rather than just a specific field on that page.