- 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.
160 lines
5.2 KiB
Python
160 lines
5.2 KiB
Python
"""Reusable OpenAPI building blocks for the HOMM API documentation.
|
|
|
|
Everything in this module is presentation-only: it describes the shapes the API
|
|
already returns and is used by ``drf-spectacular`` to render Swagger/ReDoc.
|
|
"""
|
|
|
|
from drf_spectacular.extensions import OpenApiAuthenticationExtension
|
|
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse
|
|
from rest_framework import serializers
|
|
|
|
|
|
class IntegrationTokenAuthenticationScheme(OpenApiAuthenticationExtension):
|
|
target_class = "apps.common.authentication.IntegrationTokenAuthentication"
|
|
name = "IntegrationToken"
|
|
|
|
def get_security_definition(self, auto_schema):
|
|
return {
|
|
"type": "apiKey",
|
|
"in": "header",
|
|
"name": "X-Integration-Token",
|
|
}
|
|
|
|
|
|
class ErrorBodySerializer(serializers.Serializer):
|
|
"""Machine-readable error details."""
|
|
|
|
code = serializers.CharField(
|
|
help_text="Код ошибки: HTTP-статус (400, 404, …) или строка вроде `order_not_found`."
|
|
)
|
|
message = serializers.CharField(help_text="Описание ошибки для человека.")
|
|
details = serializers.JSONField(
|
|
required=False,
|
|
help_text="Детали валидации по полям (структура зависит от ошибки).",
|
|
)
|
|
|
|
|
|
class ErrorEnvelopeSerializer(serializers.Serializer):
|
|
"""Единый конверт ошибки, который возвращает API."""
|
|
|
|
error = ErrorBodySerializer()
|
|
|
|
|
|
_ERROR_DESCRIPTIONS: dict[int, str] = {
|
|
400: "Некорректный запрос или ошибка валидации.",
|
|
401: "Требуется авторизация: access-токен отсутствует или истёк.",
|
|
403: "Недостаточно прав для этой операции.",
|
|
404: "Объект не найден.",
|
|
409: "Конфликт состояния (например, повтор с другим Idempotency-Key).",
|
|
429: "Превышен лимит запросов, попробуйте позже.",
|
|
500: "Внутренняя ошибка сервера.",
|
|
}
|
|
|
|
|
|
def error_responses(*codes: int) -> dict[int, OpenApiResponse]:
|
|
"""Builds ``responses`` entries for the shared error envelope.
|
|
|
|
Usage::
|
|
|
|
@extend_schema(responses={200: MySerializer, **error_responses(400, 401)})
|
|
"""
|
|
return {
|
|
code: OpenApiResponse(
|
|
response=ErrorEnvelopeSerializer,
|
|
description=_ERROR_DESCRIPTIONS.get(code, "Ошибка."),
|
|
)
|
|
for code in codes
|
|
}
|
|
|
|
|
|
PAGINATION_PARAMS = [
|
|
OpenApiParameter(
|
|
name="page",
|
|
type=int,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Номер страницы, начиная с 1.",
|
|
),
|
|
OpenApiParameter(
|
|
name="page_size",
|
|
type=int,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Размер страницы: по умолчанию 24, максимум 100.",
|
|
),
|
|
]
|
|
|
|
|
|
CATALOG_FILTER_PARAMS = [
|
|
OpenApiParameter(
|
|
name="category",
|
|
type=str,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Slug категории.",
|
|
),
|
|
OpenApiParameter(
|
|
name="category_id",
|
|
type=int,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="ID категории.",
|
|
),
|
|
OpenApiParameter(
|
|
name="price_min",
|
|
type=float,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Минимальная цена, включительно.",
|
|
),
|
|
OpenApiParameter(
|
|
name="price_max",
|
|
type=float,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Максимальная цена, включительно.",
|
|
),
|
|
OpenApiParameter(
|
|
name="brand",
|
|
type=str,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Бренд, регистронезависимое точное совпадение.",
|
|
),
|
|
OpenApiParameter(
|
|
name="in_stock",
|
|
type=bool,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="`true` — только товары с остатком, `false` — только без остатка.",
|
|
),
|
|
OpenApiParameter(
|
|
name="is_hit",
|
|
type=bool,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Только хиты продаж.",
|
|
),
|
|
OpenApiParameter(
|
|
name="is_new",
|
|
type=bool,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Только новинки.",
|
|
),
|
|
OpenApiParameter(
|
|
name="search",
|
|
type=str,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Поиск по названию, артикулу, бренду и описанию.",
|
|
),
|
|
OpenApiParameter(
|
|
name="ordering",
|
|
type=str,
|
|
location=OpenApiParameter.QUERY,
|
|
required=False,
|
|
description="Сортировка: `price`, `-price`, `created_at`, `-created_at`, `name`, `-name`.",
|
|
),
|
|
]
|