Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom representation of Streamfield in rest API

Tags:

api

wagtail

I have a few questions about this thread: https://groups.google.com/forum/#!topic/wagtail-developers/Z4oaCIJXYuI

I am building a headless Wagtail, with a React-based frontend, that calls Wagtail API in order to parse JSON and display content. Pretty basic.

I was wondering if it was possible to custom the output of streamfield in rest API. A few examples:

  • Get a image URL based on this example from wagtaildemo: https://github.com/wagtail/wagtaildemo/blob/api-tweaks/demo/models.py#L713-L716 (I got it working for single URLs)
  • PageChooserBlock: get a field from the targetted page

As I read in the topic linked above, the Wagtail API v1 was not ready for custom representation of Streamfield in it. Did it change since v2 ? (I didn't notice anything related in changelogs) If not, does anyone have some tips about how I could achieve such a thing?

I already planned on build a custom image model to get URL by calling api/v2/images/id, but I would love to get all these into one JSON response 🤘.

like image 388
fabienheureux Avatar asked Jan 31 '17 11:01

fabienheureux


2 Answers

As of Wagtail 1.9, you can modify the API representation of the Block in the StreamField by overriding the get_api_representation() method on the Block.

For your example we can override the method on the ImageChooserBlock itself:

import wagtail 
from rest_framework import serializers

class ImageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = wagtail.images.get_image_model()
        fields = ['title', 'file', 'width', 'height', 'file_size']

class APIImageChooserBlock(ImageChooserBlock):
    def get_api_representation(self, value, context=None):
        return ImageSerializer(context=context).to_representation(value)

@wagtail.snippets.models.register_snippet
class MySnippetForAPI(models.Model):
    title = models.CharField(max_length=80)
    content = StreamField([
        ('heading', blocks.CharBlock()),
        ('paragraph', blocks.RichTextBlock()),
        ('image', APIImageChooserBlock())
    ])

Code updated for Wagtail 2.0+

https://github.com/wagtail/wagtail/blob/b6ee2db6ac8dbf4b47a81f4b2684b7aca8cc2501/wagtail/wagtailcore/blocks/base.py#L244

like image 158
probabble Avatar answered Oct 13 '22 01:10

probabble


Adding onto the very helpful answer by probabble, you can also use get_rendition inside a StreamField block by adding a SerializerMethodField:

# serializers.py
# Explicitly importing since models are not loaded when serializers initialized

from wagtail.wagtailimages.models import Image as WagtailImage

class WagtailImageSerializer(serializers.ModelSerializer):
    url = serializers.SerializerMethodField()

    class Meta:
        model = WagtailImage
        fields = ['title', 'url']

    def get_url(self, obj):
        return obj.get_rendition('fill-300x186|jpegquality-60').url

# blocks.py

from .serializers import WagtailImageSerializer 

class APIImageChooserBlock(ImageChooserBlock):
    def get_api_representation(self, value, context=None):
        return WagtailImageSerializer(context=context).to_representation(value)

In this example, we only return the title and url of the image.

like image 40
lightstrike Avatar answered Oct 13 '22 02:10

lightstrike