Document the API in Swagger with tags, parameters and examples
- Add OpenAPI tags for the seven API groups and a full description (auth, error envelope, pagination, idempotency) in SPECTACULAR_SETTINGS - Annotate every endpoint with @extend_schema: summary, description, query parameters, request/response examples and error responses - Add shared schema helpers in apps/common/schema.py: ErrorEnvelope, error_responses(), pagination and catalog filter parameters - Document JWT login and token refresh that simplejwt ships without docs - Add ReDoc at /api/redoc/ next to Swagger UI at /api/docs/ - Add export_api_docs management command rendering the schema into a standalone HTML reference (no CDN) and commit docs/api-reference.html - Describe the documentation entry points in docs/architecture.md Schema validates cleanly: 41 operations, 0 warnings.
This commit is contained in:
1 parent
756f40353b
commit
f6c61ff8da
14 files changed
+2038
-9
No files matched your search
@@ -1,7 +1,10 @@
|
||||
from drf_spectacular.utils import OpenApiExample, extend_schema, extend_schema_view
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
|
||||
from apps.common.schema import CATALOG_FILTER_PARAMS, PAGINATION_PARAMS, error_responses
|
||||
|
||||
from .filters import ProductFilter
|
||||
from .models import Category, Product
|
||||
from .serializers import (
|
||||
@@ -10,7 +13,27 @@ from .serializers import (
|
||||
ProductListSerializer,
|
||||
)
|
||||
|
||||
TAGS = ["Каталог"]
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
list=extend_schema(
|
||||
tags=TAGS,
|
||||
summary="Категории",
|
||||
description=(
|
||||
"Плоский список активных категорий. Иерархия задаётся полем `parent` "
|
||||
"(ID родительской категории), поэтому дерево собирается на клиенте без "
|
||||
"дополнительных запросов. Данные приходят из 1С."
|
||||
),
|
||||
responses={200: CategorySerializer(many=True)},
|
||||
),
|
||||
retrieve=extend_schema(
|
||||
tags=TAGS,
|
||||
summary="Категория по slug",
|
||||
description="Карточка категории: название, родитель, изображение и порядок сортировки.",
|
||||
responses={200: CategorySerializer, **error_responses(404)},
|
||||
),
|
||||
)
|
||||
class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
queryset = Category.objects.filter(is_active=True).select_related("parent")
|
||||
serializer_class = CategorySerializer
|
||||
@@ -18,6 +41,56 @@ class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
pagination_class = None
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
list=extend_schema(
|
||||
tags=TAGS,
|
||||
summary="Список товаров",
|
||||
description=(
|
||||
"Витрина каталога: только активные товары, постранично.\n\n"
|
||||
"Поддерживает фильтры по категории, цене, бренду и наличию, поиск по "
|
||||
"названию/артикулу/бренду/описанию и сортировку. Все параметры "
|
||||
"необязательны и комбинируются между собой."
|
||||
),
|
||||
parameters=[*CATALOG_FILTER_PARAMS, *PAGINATION_PARAMS],
|
||||
responses={200: ProductListSerializer(many=True), **error_responses(400)},
|
||||
examples=[
|
||||
OpenApiExample(
|
||||
"Товар в списке",
|
||||
value={
|
||||
"id": 42,
|
||||
"slug": "kurtka-homm-softshell",
|
||||
"name": "Куртка HOMM Softshell",
|
||||
"sku": "HM-1042",
|
||||
"brand": "HOMM",
|
||||
"price": "12990.00",
|
||||
"old_price": "14990.00",
|
||||
"stock_status": "in_stock",
|
||||
"is_hit": True,
|
||||
"is_new": False,
|
||||
"main_image": "https://cdn.example.com/products/hm-1042/main.jpg",
|
||||
"category": {
|
||||
"id": 7,
|
||||
"name": "Верхняя одежда",
|
||||
"slug": "verhnyaya-odezhda",
|
||||
"parent": 1,
|
||||
"image_url": "",
|
||||
"sort_order": 10,
|
||||
},
|
||||
},
|
||||
response_only=True,
|
||||
),
|
||||
],
|
||||
),
|
||||
retrieve=extend_schema(
|
||||
tags=TAGS,
|
||||
summary="Карточка товара",
|
||||
description=(
|
||||
"Полные данные товара: описание, характеристики (объект «ключ-значение»), "
|
||||
"остаток и галерея изображений. Изображения отдаются ссылками."
|
||||
),
|
||||
responses={200: ProductDetailSerializer, **error_responses(404)},
|
||||
),
|
||||
)
|
||||
class ProductViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
queryset = (
|
||||
Product.objects.filter(is_active=True)
|
||||
@@ -44,14 +117,43 @@ class ProductViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
queryset = queryset.filter(is_new=True)
|
||||
return queryset
|
||||
|
||||
@extend_schema(
|
||||
tags=TAGS,
|
||||
summary="Хиты продаж",
|
||||
description=(
|
||||
"Товары с флагом «Хит». Флаг приходит из 1С и не вычисляется на сайте. "
|
||||
"Поддерживает те же фильтры и сортировку, что и общий список."
|
||||
),
|
||||
parameters=[*CATALOG_FILTER_PARAMS, *PAGINATION_PARAMS],
|
||||
responses={200: ProductListSerializer(many=True), **error_responses(400)},
|
||||
)
|
||||
@action(detail=False, methods=["get"])
|
||||
def hits(self, request):
|
||||
return self.list(request)
|
||||
|
||||
@extend_schema(
|
||||
tags=TAGS,
|
||||
summary="Новинки",
|
||||
description=(
|
||||
"Товары с флагом «Новинка». Поддерживает те же фильтры и сортировку, "
|
||||
"что и общий список."
|
||||
),
|
||||
parameters=[*CATALOG_FILTER_PARAMS, *PAGINATION_PARAMS],
|
||||
responses={200: ProductListSerializer(many=True), **error_responses(400)},
|
||||
)
|
||||
@action(detail=False, methods=["get"])
|
||||
def new(self, request):
|
||||
return self.list(request)
|
||||
|
||||
@extend_schema(
|
||||
tags=TAGS,
|
||||
summary="Похожие товары",
|
||||
description=(
|
||||
"До 8 активных товаров из той же категории, кроме самого товара. "
|
||||
"Без пагинации."
|
||||
),
|
||||
responses={200: ProductListSerializer(many=True), **error_responses(404)},
|
||||
)
|
||||
@action(detail=True, methods=["get"])
|
||||
def related(self, request, slug=None):
|
||||
product = self.get_object()
|
||||
|
||||
Reference in new issue
Block a user