Learn Wagtail Course

How to Enable the v2 API to Create a Headless CMS

You've undoubtedly stumbled across a website that's fluid and smooth. Pages transition without any flashing. And everything seems to be loading dynamically. Well, that's a progressive web app (PWA) or single page application (SPA). It acts as if it's an application on your mobile device. But in reality, it's just a website wearing a really good disguise.

The first step you'll need to take to start creating a PWA is enabling Wagtails existing support for a JSONified output. This is actually very easy to do. Let's install the existing apps.

base.py

Open your base.py file and add the following lines to your INSTALLED_APPS

INSTALLED_APPS = [
    # ...
    'wagtail.api.v2',
    # ...
    'rest_framework',
]

api.py

If you're starting a new (or close-to-new) project, you shouldn't already have an api.py file. If you don't, make a new file beside urls.py and name it api.py. Then add the following code.

# Our imports 
from wagtail.api.v2.endpoints import PagesAPIEndpoint
from wagtail.api.v2.router import WagtailAPIRouter
from wagtail.images.api.v2.endpoints import ImagesAPIEndpoint
from wagtail.documents.api.v2.endpoints import DocumentsAPIEndpoint

# Init the Wagtail Router
api_router = WagtailAPIRouter('wagtailapi')

# Register 3 API endpoints: Pages, Images and Documents
api_router.register_endpoint('pages', PagesAPIEndpoint)
api_router.register_endpoint('images', ImagesAPIEndpoint)
api_router.register_endpoint('documents', DocumentsAPIEndpoint)

I mentioned this file should be beside your urls.py file, but it doesn't need to be, it just makes the next step 1% easier.

urls.py

Lastly, we need to add 2 lines to our urls.py file.

# ... all your other imports
from .api import api_router


urlpatterns = [
    # ...
    # This line MUST come before the bottom url pattern
    url(r'^api/v2/', api_router.urls),
    # ...
    url(r'', include(wagtail_urls)),
]

Accessing your API

To access your API, you'll need to open http://localhost:8000/api/v2/pages/. This is your list view of all your Wagtail pages. At this point, your custom fields will not show up, just the default Wagtail Page fields will show up.

The Git Commit

Want to see the entire Git Commit? No problem. The link to the Git Commit here will show you all 12 lines we added to our Wagtail website.

Was this helpful to you?

Sharing is caring. Help the community by sharing this article.