Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

wagtail-ninja: Seamless API Integration for Wagtail with Django Ninja

wagtail-ninja is an alpha-version package designed to effortlessly expose your Wagtail pages and redirects via a robust Django Ninja API. Leverage the power of type hints and fast API development that Django Ninja provides, bringing a modern API experience to your Wagtail projects.

Installation

wagtail-ninja is available on PyPI. You can install it using pip:

pip install wagtail-ninja

git attributes

# .gitattributes
*generated_schemas.py linguist-generated=true
generated_api.py linguist-generated=true

GitHub relies on a library called Linguist. By flagging these files as linguist-generated, GitHub will automatically collapse them in the Pull Request "Files Changed" tab with a note saying "Some files were hidden because they are generated." This keeps their code reviews clean.

Quick Usage

Integrate wagtail-ninja into your Wagtail project with just a few lines of code.

1. Define Your API Routers

Create an api.py file within your Django app to set up your Django Ninja API and include the wagtail-ninja routers:

# some/path/api.py
from ninja import NinjaAPI
from wagtail_ninja.router import WagtailNinjaPagesRouter, WagtailNinjaRedirectsRouter

# Initialize your Django Ninja API - see https://django-ninja.dev/tutorial/ for more information
api = NinjaAPI()

# Add the Wagtail Pages and Redirects routers
api.add_router("/pages/", WagtailNinjaPagesRouter())
api.add_router("/redirects/", WagtailNinjaRedirectsRouter())

2. Include API URLs

Link your new Ninja API to your project's urls.py:

# your_project/urls.py
from django.urls import path

# Import your Ninja API instance
from some.path.api import api as ninja_api

urlpatterns = [
    # ... other Wagtail and Django paths
    
    # Expose your Wagtail Ninja API
    path("api/wagtail/v3/", ninja_api.urls),
]

Features & Benefits

Once integrated, you'll immediately gain:

  • Interactive API Documentation: Access the OpenAPI Ninja UI at http://localhost:8000/api/wagtail/v3/docs (adjust port and path as per your configuration). This provides a user-friendly interface to explore your API endpoints.
  • Programmatic Schema Access: Retrieve your API's OpenAPI schema (for code generation, testing, etc.) from http://localhost:8000/api/wagtail/v3/openapi.json.
  • Type Hinting Benefits: Leverage Django Ninja's core strength for better code clarity and developer experience.

Configuration

StreamField Block Type Hinting (⚠ experimental)

wagtail-ninja includes an experimental feature to provide more specific type hints for StreamField blocks in your API schema.

To enable this, set the following in your Django settings:

# settings.py
WAGTAIL_NINJA_TYPE_STREAMFIELDBLOCKS = True

If this setting is False (the default) or not set, StreamField values will be typed as unknown in the OpenAPI schema. Enabling it should work for the most part, but it will likely give you many errors because any custom get_api_reprensentation you have will likely clash with the then expected result type.

Migrating from DRF-Specific Code

If you're transitioning from a djangorestframework (DRF) approach or have custom API field definitions, here are key considerations:

  • DRF Serializers are Not Supported: wagtail-ninja is built on Django Ninja, which uses Pydantic for serialization. Therefore, traditional DRF serializers (e.g., APIField("myfield", serializer=MySerializer())) are not compatible.
  • Custom Field Resolution: For fields requiring custom serialization logic, Wagtail-Ninja will look for a resolve_<field_name> method within your custom MyPage(Page). This allows you to define how a specific field's value is processed before being returned by the API.

Annotating api_fields for Type Hinting

When using api_fields on your Wagtail Page models to expose custom methods, you might encounter circular import issues when trying to type-hint the return values with Django Ninja ModelSchemas.

Consider this common scenario:

# schema.py
from ninja import ModelSchema
from .models import MyPage, OtherPage

class OtherPageSchema(ModelSchema):
    class Meta:
        model = OtherPage

class MyPageSchema(ModelSchema):
    class Meta:
        model = MyPage
# models.py
# This will cause a circular import if OtherPageSchema is imported at the top level
# from .schema import OtherPageSchema 

class MyPage(Page):
    api_fields = ['related_otherpage']

    # Attempting to type-hint directly leads to circular dependency
    # def related_otherpage(self) -> OtherPageSchema: 
    #    related = OtherPage.objects.first() # Example logic
    #    return OtherPageSchema.from_orm(related)

The current "best" solution to avoid circular dependencies while still providing accurate type hints for Django Ninja is to define a static method that returns the schema class, and then attach it to your custom field method:

# models.py
from wagtail.models import Page
from django.db import models

class OtherPage(Page):
    # Your fields for OtherPage
    pass

class MyPage(Page):
    # Your fields for MyPage
    api_fields = ['related_otherpage']

    def related_otherpage(self):
        # Local import to avoid circular dependency at module load time
        from .schema import OtherPageSchema 
        related = OtherPage.objects.first() # Your logic to get the related object(s)
        return OtherPageSchema.from_orm(related)

    @staticmethod
    def type_fn():
        # This static method returns the schema class itself
        from .schema import OtherPageSchema
        return OtherPageSchema

    # Attach the type_fn to your method with a special attribute
    related_otherpage._wagtail_ninja_type_fn = type_fn

This pattern ensures that wagtail-ninja (and Django Ninja) can correctly infer the response schema for your custom api_fields without causing import errors.

Contributing & Support

wagtail-ninja is currently in an alpha state. Your contributions, feedback, and bug reports are highly welcome to help shape its development!

AI

yes, some LLM helped with the README.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

wagtail_ninja-0.2b5.tar.gz (15.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

wagtail_ninja-0.2b5-py3-none-any.whl (20.4 kB view details)

Uploaded Python 3

File details

Details for the file wagtail_ninja-0.2b5.tar.gz.

File metadata

  • Download URL: wagtail_ninja-0.2b5.tar.gz
  • Upload date:
  • Size: 15.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"TUXEDO OS","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for wagtail_ninja-0.2b5.tar.gz
Algorithm Hash digest
SHA256 ffe150f159d2323209bfaf000959eb4d012b20ddbb0448df58f25a94e3e6a4bf
MD5 caf8ee85250954bed209de142d1725b9
BLAKE2b-256 0d7732f2580a431bffec03235cbcbe28cb33f4bc6cf561a3ff6ddd3d0b6d0868

See more details on using hashes here.

File details

Details for the file wagtail_ninja-0.2b5-py3-none-any.whl.

File metadata

  • Download URL: wagtail_ninja-0.2b5-py3-none-any.whl
  • Upload date:
  • Size: 20.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"TUXEDO OS","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for wagtail_ninja-0.2b5-py3-none-any.whl
Algorithm Hash digest
SHA256 213f13596329847cf2f5bdd91b8bb4f05896c17742e2db07006cd0a61bcb5f14
MD5 c4af641ffa4b37d9289b3b9c8c53c8e2
BLAKE2b-256 af83cad7b1abaa9204b65533b3a342ae91ab22ddafe97ce273d658d65b8a32b5

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.2b5 This release

2 files

0.1.26

2 files

0.1.25

2 files

0.1.24

2 files

0.1.23

2 files

0.1.22

2 files

0.1.21

2 files

0.1.20

2 files

0.1.19

2 files

0.1.18

2 files

0.1.17

2 files

0.1.16.post1

2 files

0.1.16

2 files

0.1.15

2 files

0.1.14

2 files

0.1.13

2 files

0.1.12

2 files

0.1.11

2 files

0.1.10

2 files

0.1.9

2 files

0.1.8

2 files

0.1.7

2 files

0.1.6

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page