Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wagtail API - how to expose snippets

Imagine I have a Snippet and a Page containing it:

@register_snippet
class MySnippet(models.Model):
    content = models.CharField(max_length=255)


class MyPage(Page):
    snippet = models.ForeignKey('MySnippet', null=True, blank=True, on_delete=models.SET_NULL, related_name='+')

    api_fields = [
        APIFiled('snippet')
    ]

Now in the wagtail API page endpoint this page will look like this:

{
    "id": 1,
    "meta": { ... },
    "snippet": {
        "id": 1,
        "meta": {
            "type": "my_module.MySnippet"
        }
    }
}

What can I do to make this endpoint displaying snippet's content?

Also, how do I create a separate API endpoint only for snippets?

like image 431
mnowotka Avatar asked Dec 23 '22 04:12

mnowotka


2 Answers

I'm not sure how to answer the main question, but I can help with creating separate API endpoints for snippets.

You have to create an endpoints.py file in your app root, using the existing Wagtail endpoint classes as a base, such as BaseAPIEndpoint

Then, register the new endpoint in your api.py file.

endpoints.py

from wagtail.api.v2.endpoints import BaseAPIEndpoint
from .models import MySnippetModel

class MySnippetModelAPIEndpoint(BaseAPIEndpoint):

    model = MySnippetModel

    body_fields = BaseAPIEndpoint.body_fields + [
        'field_1',
        'field_2',
        'field_3',
    ]

    listing_default_fields = BaseAPIEndpoint.listing_default_fields = [
        'field_1',
        'field_2',
        'field_3',
    ]

api.py

from .endpoints import MySnippetModelAPIEndpoint

...

sua_api_router.register_endpoint('snippets', MySnippetModelAPIEndpoint)

I would also look at the endpoints.py file in Wagtail core, so you can see what else you can extend or modify.

https://github.com/wagtail/wagtail/blob/master/wagtail/api/v2/endpoints.py

like image 136
LazerFriends Avatar answered Dec 25 '22 18:12

LazerFriends


Here's how I did it, it was a simple enough representation though in my case

from rest_framework import serializers

class MyPage(Page):
    snippet = models.ForeignKey('MySnippet', null=True, blank=True, on_delete=models.SET_NULL, related_name='+')

    api_fields = [
        APIField('snippet', serializer=serializers.StringRelatedField(many=True))
    ]

And you can add a 'str' method to your snippet

@register_snippet
class MySnippet(models.Model):
    content = models.CharField(max_length=255)

        def __str__(self):
            return self.content
like image 33
Udit Agarwal Avatar answered Dec 25 '22 18:12

Udit Agarwal