Add endpoint to list page URLs

I use this for my quick link grabber script
This commit is contained in:
Jake Howard 2022-08-23 09:23:22 +01:00
parent 4a82d1262d
commit f140e8107d
Signed by: jake
GPG key ID: 57AFB45680EDD477
4 changed files with 63 additions and 1 deletions

View file

@ -0,0 +1,13 @@
from rest_framework import serializers
from wagtail.models import Page
class PageLinkSerializer(serializers.ModelSerializer):
full_url = serializers.SerializerMethodField()
class Meta:
model = Page
fields = read_only_fields = ["full_url", "title"]
def get_full_url(self, page: Page) -> str:
return page.get_full_url(request=self.context["request"])

29
website/api/tests.py Normal file
View file

@ -0,0 +1,29 @@
from django.urls import reverse
from rest_framework.test import APISimpleTestCase, APITestCase
from website.common.factories import ContentPageFactory
from website.home.models import HomePage
class PingAPIViewTestCase(APISimpleTestCase):
url = reverse("api:ping")
def test_accessible(self) -> None:
response = self.client.get(self.url)
self.assertEqual(response.status_code, 200)
class PageLinksAPIViewTestCase(APITestCase):
url = reverse("api:page-links")
@classmethod
def setUpTestData(cls) -> None:
cls.home_page = HomePage.objects.get()
for _ in range(5):
ContentPageFactory(parent=cls.home_page)
def test_accessible(self) -> None:
with self.assertNumQueries(3):
response = self.client.get(self.url)
self.assertEqual(response.status_code, 200)

View file

@ -8,7 +8,10 @@ from . import views
app_name = "api" app_name = "api"
api_urlpatterns = [path("ping", views.PingAPIView.as_view(), name="ping")] api_urlpatterns = [
path("ping", views.PingAPIView.as_view(), name="ping"),
path("page-links", views.PageLinksAPIView.as_view(), name="page-links"),
]
schema_view = get_schema_view( schema_view = get_schema_view(
openapi.Info( openapi.Info(

View file

@ -1,6 +1,11 @@
from django.http.request import HttpRequest from django.http.request import HttpRequest
from rest_framework.generics import ListAPIView
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.views import APIView from rest_framework.views import APIView
from wagtail.models import Page
from wagtail.query import PageQuerySet
from . import serializers
class PingAPIView(APIView): class PingAPIView(APIView):
@ -10,3 +15,15 @@ class PingAPIView(APIView):
def get(self, request: HttpRequest) -> Response: def get(self, request: HttpRequest) -> Response:
return Response("PONG") return Response("PONG")
class PageLinksAPIView(ListAPIView):
serializer_class = serializers.PageLinkSerializer
def get_queryset(self) -> PageQuerySet:
return (
Page.objects.live()
.exclude(depth__lte=1)
.only("id", "url_path", "title")
.order_by("title")
)