Search code examples
wagtailwagtail-apiv2

Filtering on fields doesn't apply the actual fitler set


Extending the BaseAPIEndpoint on a custom page model exposes its pages through the api, which is great, however, when I try to apply a field filter, it is not applied, and the response returns all pages regardless. The documentation has no mention of this.

for example:

endpoints.py

from wagtail.api.v2.endpoints import BaseAPIEndpoint
from app.models import MyPageClass

class MyPageClassAPIEndpoint(BaseAPIEndpoint):
    refname= MyPageClass
    model = refname

api.py:

from wagtail.api.v2.router import WagtailAPIRouter
from .endpoints import MyPageClassAPIEndpoint

# Create the router. "wagtailapi" is the URL namespace
api_router = WagtailAPIRouter('wagtailapi')
api_router.register_endpoint('refname', MyPageClassAPIEndpoint)

If i try to add a filter when i call my endpoint:

http://localhost:8000/api/v2/refname/?id=6

the repsonse will return all the records associated to my model.

{
"meta": {
    "total_count": 2
},
"items": [
    {
        "id": 6,
        "meta": {
            "type": "app.MyPageClass",
            "detail_url": "http://localhost/api/v2/pages/6/"
        }
    },
    {
        "id": 7,
        "meta": {
            "type": "app.MyPageClass",
            "detail_url": "http://localhost/api/v2/pages/7/"
        }
    }
  ]
}

How can I achieve filtering on my endpoint while extending the BaseAPIEndpoint class?


Solution

  • You will need to import the FieldsFilter Class from wagtail.api.v2.filters and then append it to the filter_backends of your custom endpoint's Class as follows:

    from wagtail.api.v2.endpoints import BaseAPIEndpoint
    from wagtail.api.v2.filters import FieldsFilter
    from app.models import MyPageClass
    
    class MyPageClass(BaseAPIEndpoint):
        refname= MyPageClass
        model = refname
        BaseAPIEndpoint.filter_backends.append(FieldsFilter)
    

    After doing so, your endpoint will now accept filtering on fields.

    http://localhost:8000/api/v2/refname/?id=6

    {
    "meta": {
        "total_count": 1
    },
    "items": [
        {
            "id": 6,
            "meta": {
                "type": "projects.ProjectTaskPage",
                "detail_url": "http://localhost/api/v2/pages/6/"
            }
        }
      ]
    
    }