在Wagtail 网站中为自定义内容类型创建 API 端点路径
在 在Wagtail网站中提供 RESTful API 服务 一文中,介绍了怎样为Wagtail 内置的页面、图片、文档 等类型的内容配置API 端点路径,其中也提到,如果要增加新的内容类型,可以继承路径基类 wagtail.api.v2.views.BaseAPIViewSet ,本文以类型为BlogCategory 的Snippet 为例,介绍怎样为其创建API 路径端点。
blog 应用下的BlogCategory 类如下:
from django.db import models
from wagtail.admin.edit_handlers import (FieldPanel, FieldRowPanel,
InlinePanel, MultiFieldPanel,
PageChooserPanel, StreamFieldPanel)
@register_snippet
class BlogCategory(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(unique=True, max_length=80)
panels = [
FieldPanel('name'),
FieldPanel('slug'),
]
def __str__(self):
return self.name
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
在应用下创建 endpoints.py,内容如下
from wagtail.api.v2.views import BaseAPIViewSet
from blog.models import BlogCategory
class BlogCategoryAPIViewSet(BaseAPIViewSet):
model = BlogCategory
body_fields = BaseAPIViewSet.body_fields + [
'id',
'name',
'slug',
]
listing_default_fields = BaseAPIViewSet.listing_default_fields = [
'id',
'name',
'slug',
'type',
'detail_url',
]
在api.py 中,增加如下内容(请参考 在Wagtail网站中提供 RESTful API 服务 )
from .endpoints import BlogCategoryAPIViewSet
...
api_router.register_endpoint('categories', BlogCategoryAPIViewSet)
当然还需要确保urls.py 中,urlpatterns 列表中增加了如下路由
path('api/v2/', api_router.urls),
最后,重启服务后,就通过访问API获取到BlogCategory 的列表了,例如 /api/v2/categories/?format=json
{
"meta": {
"total_count": 2
},
"items": [
{
"id": 1,
"meta": {
"type": "blog.BlogCategory",
"detail_url": "http://api.example.com/api/v2/categories/1/",
},
"name": "Test",
"slug": "category-test-1"
},
{
"id": 2,
"meta": {
"type": "blog.BlogCategory",
"detail_url": "http://api.example.com/api/v2/categories/2/",
},
"name": "Hello",
"slug": "category-test-2"
}
]
}
冀公网安备 13010402001886号