Metadata-Version: 2.4
Name: drf-apischema
Version: 0.1.17
Summary: API schema generator and validator for Django REST framework
Project-URL: Repository, https://github.com/hmeqo/drf-apischema.git
Project-URL: Issues, https://github.com/hmeqo/drf-apischema/issues
Author-email: hmeqo <hmeqo@qq.com>
License: MIT License
        
        Copyright (c) 2024 Hmeqo
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: codegen,django,django-rest-framework,django-rest-swagger,documentation,drf,drf-openapi,drf-yasg,openapi,schema,swagger,swagger-codegen
Classifier: Framework :: Django
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Requires-Dist: django
Requires-Dist: django-restframework
Requires-Dist: drf-yasg
Requires-Dist: rich
Requires-Dist: sqlparser
Description-Content-Type: text/markdown

# DRF APISchema

Based on [`drf-yasg`](https://drf-yasg.readthedocs.io/en/latest/), automatically generate API documentation, validate queries, bodies, and permissions, handle transactions, and log SQL queries.  
This can greatly speed up development and make the code more readable.

## Features

- Auto generate API documentation and routes

- Validate queries, bodies, and permissions

- Handle transactions

- Log SQL queries

- Simple to use

```python
@apischema(permissions=[IsAdminUser], body=UserIn, response=UserOut)
def create(self, request: ASRequest[UserIn]):
    print(request.serializer, request.validated_data)
    return UserOut(request.serializer.save()).data
```

![swagger](https://github.com/user-attachments/assets/20315efb-5d0c-4e69-9384-926d4cc4ea7d)

## Installation

Install `drf-apischema` from PyPI

```bash
pip install drf-apischema
```

Configure your project `settings.py` like this

```py
INSTALLED_APPS = [
    # ...
    "drf_yasg",
    "rest_framework",
    # ...
]

STATIC_URL = "static/"

# Ensure you have been defined it
STATIC_ROOT = BASE_DIR / "static"

# STATICFILES_DIRS = []
```

Run `collectstatic`

```bash
python manage.py collectstatic --noinput
```

## Quickstart

serializers.py

```python
from django.contrib.auth.models import User
from rest_framework import serializers


class UserOut(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username"]


class SquareOut(serializers.Serializer):
    result = serializers.IntegerField()


class SquareQuery(serializers.Serializer):
    n = serializers.IntegerField(default=2)
```

views.py

```python
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.viewsets import GenericViewSet

from drf_apischema import ASRequest, apischema

from .serializers import SquareOut, SquareQuery, TestOut


class TestViewSet(GenericViewSet):
    """Tag here"""

    queryset = User.objects.all()
    serializer_class = TestOut
    permission_classes = [IsAuthenticated]

    # Define a view that requires permissions
    @apischema(permissions=[IsAdminUser], extra_tags=["tag1", "tag2"])
    def list(self, request):
        """List all

        Document here
        xxx
        """
        # Note that apischema won't automatically process the response with the
        # declared response serializer, but it will wrap it with
        # rest_framework.response.Response
        # So you don't need to manually wrap it with Response
        return self.get_serializer([{"id": 1}, {"id": 2}, {"id": 3}]).data

    @action(methods=["GET"], detail=False)
    @apischema(query=SquareQuery, response=SquareOut, transaction=False)
    def square(self, request: ASRequest[SquareQuery]):
        """The square of a number"""
        # The request.serializer is an instance of SquareQuery that has been validated
        # print(request.serializer)

        # The request.validated_data is the validated data of the serializer
        n: int = request.validated_data["n"]
        return SquareOut({"result": n * n}).data

    @action(methods=["GET"], detail=True)
    @apischema()
    def echo(self, request, pk):
        """Echo the request"""
        return self.get_serializer(self.get_object()).data
```

urls.py

```python
from django.urls import include, path
from rest_framework.routers import DefaultRouter

from drf_apischema.urls import api_path

from .views import *

router = DefaultRouter()
router.register("test", TestViewSet, basename="test")


urlpatterns = [
    # Auto-generate /api/swagger/ and /api/redoc/ for documentation
    api_path("api/", [path("", include(router.urls))])
]
```

## settings

settings.py

```python
DEFAULT_SETTINGS = {
    # Enable transaction wrapping for APIs
    "TRANSACTION": True,
    # Enable SQL logging when in debug mode
    "SQL_LOGGING": True,
    # Indent SQL queries
    "SQL_LOGGING_REINDENT": True,
    # Override the default swagger auto schema
    "OVERRIDE_SWAGGER_AUTO_SCHEMA": True,
    # Show permissions in description
    "SHOW_PERMISSIONS": True,
}
```
