0
votes

My company is running Wagtail headless, using only the API, to power parts of an existing web intranet. We'd like to include a customized "edit bar" at the top of every page in the main web application, which points to the "edit" page of the matching record in Wagtail. We're going to pass the current user's along with the request. Then we'd like to include a custom field in the Wagtail API response, for all requests which indicates that user's permission to edit that resource.

To illustrate, I'm looking to make a request like this:

http://localhost:32891/api/v2/page/?fields=place_id,location_slug&type=destination.DestinationPage&[email protected]

Which would result (in a perfect world) in a response like this:

{
    "custom": {
        "can_edit": True,
    },
    "meta": {
        "total_count": 10
    },
    "items": [
        {
            "id": 1,
            "title": "Test blog post",
            "published_date": "2016-08-30",
        },
    ]
}

The API indicates that you can include custom fields in the Page (or Image and Document), API response, but ideally I'd like for this object to be available for all "things" via our API. This means that if someone requests a document, I wouldn't have to manually return this field for each individual model.

I'm thinking it might be possible to override the behavior of the BaseAPIEndpoint?

1

1 Answers

1
votes

Here's one way that we figured out how to do it. The "SecuredPagesAPIEndpoint" pages class already existed in our system.

class SecuredPagesAPIEndpoint(PagesAPIEndpoint):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)

    def listing_view(self, request):
        response = super().listing_view(request)

        # create custom response object
        # this object will contain any number of custom properties that we want to
        # expose to consumers of this API
        response.data['custom'] = {
            'foo': 'BAR'
        }

        return response

and this is the resulting JSON:

{
    "meta": {
        "total_count": 1
    },
    "items": [
        {
            "id": 8,
            "meta": {
                "type": "destination.DestinationPage",
                "detail_url": "http://localhost/api/v2/page/8/",
                "html_url": "http://localhost/my-page-title/",
                "slug": "my-page-title",
                "first_published_at": "2019-02-19T17:15:13.952708Z"
            },
            "title": "My page title"
        }
    ],
    "custom": {
        "FOO": 'BAR'
    }
}