configuration.rst 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. ==================================
  2. Wagtail API v2 Configuration Guide
  3. ==================================
  4. This section of the docs will show you how to set up a public API for your
  5. Wagtail site.
  6. Even though the API is built on Django REST Framework, you do not need to
  7. install this manually as it is already a dependency of Wagtail.
  8. Basic configuration
  9. ===================
  10. Enable the app
  11. --------------
  12. Firstly, you need to enable Wagtail's API app so Django can see it.
  13. Add ``wagtail.api.v2`` to ``INSTALLED_APPS`` in your Django project settings:
  14. .. code-block:: python
  15. # settings.py
  16. INSTALLED_APPS = [
  17. ...
  18. 'wagtail.api.v2',
  19. ...
  20. ]
  21. Optionally, you may also want to add ``rest_framework`` to ``INSTALLED_APPS``.
  22. This would make the API browsable when viewed from a web browser but is not
  23. required for basic JSON-formatted output.
  24. Configure endpoints
  25. -------------------
  26. Next, it's time to configure which content will be exposed on the API. Each
  27. content type (such as pages, images and documents) has its own endpoint.
  28. Endpoints are combined by a router, which provides the url configuration you
  29. can hook into the rest of your project.
  30. Wagtail provides three endpoint classes you can use:
  31. - Pages :class:`wagtail.api.v2.endpoints.PagesAPIEndpoint`
  32. - Images :class:`wagtail.images.api.v2.endpoints.ImagesAPIEndpoint`
  33. - Documents :class:`wagtail.documents.api.v2.endpoints.DocumentsAPIEndpoint`
  34. You can subclass any of these endpoint classes to customise their functionality.
  35. Additionally, there is a base endpoint class you can use for adding different
  36. content types to the API: :class:`wagtail.api.v2.endpoints.BaseAPIEndpoint`
  37. For this example, we will create an API that includes all three builtin content
  38. types in their default configuration:
  39. .. code-block:: python
  40. # api.py
  41. from wagtail.api.v2.endpoints import PagesAPIEndpoint
  42. from wagtail.api.v2.router import WagtailAPIRouter
  43. from wagtail.images.api.v2.endpoints import ImagesAPIEndpoint
  44. from wagtail.documents.api.v2.endpoints import DocumentsAPIEndpoint
  45. # Create the router. "wagtailapi" is the URL namespace
  46. api_router = WagtailAPIRouter('wagtailapi')
  47. # Add the three endpoints using the "register_endpoint" method.
  48. # The first parameter is the name of the endpoint (eg. pages, images). This
  49. # is used in the URL of the endpoint
  50. # The second parameter is the endpoint class that handles the requests
  51. api_router.register_endpoint('pages', PagesAPIEndpoint)
  52. api_router.register_endpoint('images', ImagesAPIEndpoint)
  53. api_router.register_endpoint('documents', DocumentsAPIEndpoint)
  54. Next, register the URLs so Django can route requests into the API:
  55. .. code-block:: python
  56. # urls.py
  57. from .api import api_router
  58. urlpatterns = [
  59. ...
  60. url(r'^api/v2/', api_router.urls),
  61. ...
  62. # Ensure that the api_router line appears above the default Wagtail page serving route
  63. url(r'', include(wagtail_urls)),
  64. ]
  65. With this configuration, pages will be available at ``/api/v2/pages/``, images
  66. at ``/api/v2/images/`` and documents at ``/api/v2/documents/``
  67. .. _apiv2_page_fields_configuration:
  68. Adding custom page fields
  69. -------------------------
  70. It's likely that you would need to export some custom fields over the API. This
  71. can be done by adding a list of fields to be exported into the ``api_fields``
  72. attribute for each page model.
  73. For example:
  74. .. code-block:: python
  75. # blog/models.py
  76. from wagtail.api import APIField
  77. class BlogPageAuthor(Orderable):
  78. page = models.ForeignKey('blog.BlogPage', on_delete=models.CASCADE, related_name='authors')
  79. name = models.CharField(max_length=255)
  80. api_fields = [
  81. APIField('name'),
  82. ]
  83. class BlogPage(Page):
  84. published_date = models.DateTimeField()
  85. body = RichTextField()
  86. feed_image = models.ForeignKey('wagtailimages.Image', on_delete=models.CASCADE, ...)
  87. private_field = models.CharField(max_length=255)
  88. # Export fields over the API
  89. api_fields = [
  90. APIField('published_date'),
  91. APIField('body'),
  92. APIField('feed_image'),
  93. APIField('authors'), # This will nest the relevant BlogPageAuthor objects in the API response
  94. ]
  95. This will make ``published_date``, ``body``, ``feed_image`` and a list of
  96. ``authors`` with the ``name`` field available in the API. But to access these
  97. fields, you must select the ``blog.BlogPage`` type using the ``?type``
  98. :ref:`parameter in the API itself <apiv2_custom_page_fields>`.
  99. Custom serialisers
  100. ------------------
  101. Serialisers_ are used to convert the database representation of a model into
  102. JSON format. You can override the serialiser for any field using the
  103. ``serializer`` keyword argument:
  104. .. code-block:: python
  105. from rest_framework.fields import DateField
  106. class BlogPage(Page):
  107. ...
  108. api_fields = [
  109. # Change the format of the published_date field to "Thursday 06 April 2017"
  110. APIField('published_date', serializer=DateField(format='%A $d %B %Y')),
  111. ...
  112. ]
  113. Django REST framework's serializers can all take a source_ argument allowing you
  114. to add API fields that have a different field name or no underlying field at all:
  115. .. code-block:: python
  116. from rest_framework.fields import DateField
  117. class BlogPage(Page):
  118. ...
  119. api_fields = [
  120. # Date in ISO8601 format (the default)
  121. APIField('published_date'),
  122. # A separate published_date_display field with a different format
  123. APIField('published_date_display', serializer=DateField(format='%A $d %B %Y', source='published_date')),
  124. ...
  125. ]
  126. This adds two fields to the API (other fields omitted for brevity):
  127. .. code-block:: json
  128. {
  129. "published_date": "2017-04-06",
  130. "published_date_display": "Thursday 06 April 2017"
  131. }
  132. .. _Serialisers: http://www.django-rest-framework.org/api-guide/fields/
  133. .. _source: http://www.django-rest-framework.org/api-guide/fields/#source
  134. Images in the API
  135. -----------------
  136. The :class:`~wagtail.images.api.fields.ImageRenditionField` serialiser
  137. allows you to add renditions of images into your API. It requires an image
  138. filter string specifying the resize operations to perform on the image. It can
  139. also take the ``source`` keyword argument described above.
  140. For example:
  141. .. code-block:: python
  142. from wagtail.images.api.fields import ImageRenditionField
  143. class BlogPage(Page):
  144. ...
  145. api_fields = [
  146. # Adds information about the source image (eg, title) into the API
  147. APIField('feed_image'),
  148. # Adds a URL to a rendered thumbnail of the image to the API
  149. APIField('feed_image_thumbnail', serializer=ImageRenditionField('fill-100x100', source='feed_image')),
  150. ...
  151. ]
  152. This would add the following to the JSON:
  153. .. code-block:: json
  154. {
  155. "feed_image": {
  156. "id": 45529,
  157. "meta": {
  158. "type": "wagtailimages.Image",
  159. "detail_url": "http://www.example.com/api/v2/images/12/",
  160. "tags": []
  161. },
  162. "title": "A test image",
  163. "width": 2000,
  164. "height": 1125
  165. },
  166. "feed_image_thumbnail": {
  167. "url": "http://www.example.com/media/images/a_test_image.fill-100x100.jpg",
  168. "width": 100,
  169. "height": 100
  170. }
  171. }
  172. Additional settings
  173. ===================
  174. ``WAGTAILAPI_BASE_URL``
  175. -----------------------
  176. (required when using frontend cache invalidation)
  177. This is used in two places, when generating absolute URLs to document files and
  178. invalidating the cache.
  179. Generating URLs to documents will fall back the the current request's hostname
  180. if this is not set. Cache invalidation cannot do this, however, so this setting
  181. must be set when using this module alongside the ``wagtailfrontendcache`` module.
  182. ``WAGTAILAPI_SEARCH_ENABLED``
  183. -----------------------------
  184. (default: True)
  185. Setting this to false will disable full text search. This applies to all
  186. endpoints.
  187. ``WAGTAILAPI_LIMIT_MAX``
  188. ------------------------
  189. (default: 20)
  190. This allows you to change the maximum number of results a user can request at a
  191. time. This applies to all endpoints. Set to ``None`` for no limit.