首页 > 解决方案 > 在每个 Wagtail API 响应中包含一个自定义字段

问题描述

我的公司正在无头运行 Wagtail,仅使用 API 来为现有 Web 内部网的部分提供动力。我们希望在主 Web 应用程序的每个页面顶部包含一个自定义的“编辑栏”,它指向 Wagtail 中匹配记录的“编辑”页面。我们将与请求一起传递当前用户。然后我们想在 Wagtail API 响应中包含一个自定义字段,用于指示用户编辑该资源的权限的所有请求。

为了说明,我希望提出这样的请求:

http://localhost:32891/api/v2/page/?fields=place_id,location_slug&type=destination.DestinationPage&user_email=foo@bar.com

这将导致(在一个完美的世界中)这样的响应:

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

API 表明您可以在页面(或图像和文档)、API 响应中包含自定义字段,但理想情况下,我希望此对象可通过我们的 API 用于所有“事物”。这意味着如果有人请求文档,我不必为每个单独的模型手动返回此字段。

我认为有可能覆盖BaseAPIEndpoint?

标签: wagtailwagtail-apiv2

解决方案


这是我们想出如何做到这一点的一种方法。我们的系统中已经存在“SecuredPagesAPIEndpoint”页面类。

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

这是生成的 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'
    }
}

推荐阅读