Headless CMS: Exposing Custom Page Fields to the v2 API
In the last lesson we enabled the Wagtail v2 API by writing 12 line of code. But our custom fields didn't show up. But to make these custom fields show up as JSON output in the Wagtail v2 API is really easy. In fact, it's just 4 lines of code. And for every extra field you want to expose is just one more line of code. Let's take a look at exposing a custom field in a Wagtail Page.
from django.db import models from wagtail.core.models import Page from wagtail.api import APIField class HomePage(Page): """Home page model.""" banner_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=False, on_delete=models.SET_NULL, related_name="+", ) api_fields = [ APIField("banner_image"), ]
In the above example, we're using a ForeignKey to a Wagtail Image, and near the bottom we're simply exposing that field to the v2 API. And if you opened this page in your v2 api viewer (ie
localhost:8000/api/v2/api/find/?html_path=/) you should see the
banner_image with a bunch of extra data, like a
detail_url, and even the image
And that's it! If you want to expose more fields, simply add more
APIField()'s to your
api_fields model property.
The Git Commit
The sample code in this lesson isn't great, so if you'd like to see a highlighted version of what was changed from the last lesson to this lesson, you can view the entire git commit here.
Was this helpful to you?
Sharing is caring. Help the community by sharing this article.