In the last lesson we enabled Wagtails v2 API but we didn't have access to our custom fields.. yet! In this lesson we'll learn how in just 4 lines of code we can make a custom Wagtail Page field show up in our API. And it only gets easier from there.
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.