drf-apischema


Namedrf-apischema JSON
Version 0.2.9 PyPI version JSON
download
home_pageNone
SummaryAPI schema generator and validator for Django REST framework
upload_time2025-10-07 07:42:50
maintainerNone
docs_urlNone
authorNone
requires_python>=3.11
licenseBSD 3-Clause License Copyright (c) 2025, Hmeqo Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
keywords django django-rest-framework documentation drf drf-apischema drf-spectacular openapi schema swagger
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # DRF APISchema

Based on `drf-spectacular`, 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]):
    """Description"""
    print(request.serializer, request.validated_data)
    return UserOut(request.serializer.save()).data
```

## Installation

Install `drf-apischema` from PyPI

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

Configure your project `settings.py` like this

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

REST_FRAMEWORK = {
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}

SPECTACULAR_SETTINGS = {
    "TITLE": "Your Project API",
    "DESCRIPTION": "Your project description",
    "VERSION": "1.0.0",
    "SERVE_INCLUDE_SCHEMA": False,
    'SCHEMA_PATH_PREFIX': '/api',
}
```

## Usage

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 typing import Any

from django.contrib.auth.models import User
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.viewsets import GenericViewSet

from drf_apischema import ASRequest, apischema, apischema_view

from .serializers import SquareOut, SquareQuery, UserOut

# Create your views here.


@apischema_view(
    retrieve=apischema(summary="Retrieve a user"),
)
class UserViewSet(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    """User management"""

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

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

        Document here
        xxx
        """
        return super().list(request)

    # will auto wrap it with `apischema` in `apischema_view`
    @action(methods=["post"], detail=True)
    def echo(self, request, pk):
        """Echo the request"""
        return self.get_serializer(self.get_object()).data

    @apischema(query=SquareQuery, response=SquareOut)
    @action(methods=["get"], detail=False)
    def square(self, request: ASRequest[SquareQuery]) -> Any:
        """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"]

        # 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 SquareOut({"result": n * n}).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/schema/, /api/schema/swagger/ and /api/schema/redoc/ for documentation
    api_path("api/", [path("", include(router.urls))])
]
```

## settings

settings.py

```python
DRF_APISCHEMA_SETTINGS = {
    # Enable transaction wrapping for APIs
    "TRANSACTION": True,
    # Enable SQL logging
    "SQL_LOGGING": True,
    # Indent SQL queries
    "SQL_LOGGING_REINDENT": True,
    # Use method docstring as summary and description
    "SUMMARY_FROM_DOC": True,
    # Show permissions in description
    "SHOW_PERMISSIONS": True,
    # If True, request_body and response will be empty by default if the view is action decorated
    "ACTION_DEFAULTS_EMPTY": True,
}
```

## drf-yasg version

See branch drf-yasg, it is not longer supported

## Troubleshooting

### Doesn't showed permissions description of `permission_classes`

Wrap the view with `apischema_view`.

```python
@apischema_view()
class XxxViewSet(GenericViewSet):
    permissions_classes = [IsAuthenticated]
```

### TypeError: cannot be assigned to parameter of type "_View@action"

Just annotate the return type to `Any`, as `apischema` will wrap it with `Response`.

```python
@apischema()
@action(methods=["get"], detail=False)
def xxx(self, request) -> Any:
    ...
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "drf-apischema",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": null,
    "keywords": "django, django-rest-framework, documentation, drf, drf-apischema, drf-spectacular, openapi, schema, swagger",
    "author": null,
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/ab/22/e2219948061fb8f01cfbc4e6fc918289c516791426ec845734d9dfc86c24/drf_apischema-0.2.9.tar.gz",
    "platform": null,
    "description": "# DRF APISchema\n\nBased on `drf-spectacular`, automatically generate API documentation, validate queries, bodies, and permissions, handle transactions, and log SQL queries.  \nThis can greatly speed up development and make the code more readable.\n\n## Features\n\n- Auto generate API documentation and routes\n\n- Validate queries, bodies, and permissions\n\n- Handle transactions\n\n- Log SQL queries\n\n- Simple to use\n\n```python\n@apischema(permissions=[IsAdminUser], body=UserIn, response=UserOut)\ndef create(self, request: ASRequest[UserIn]):\n    \"\"\"Description\"\"\"\n    print(request.serializer, request.validated_data)\n    return UserOut(request.serializer.save()).data\n```\n\n## Installation\n\nInstall `drf-apischema` from PyPI\n\n```bash\npip install drf-apischema\n```\n\nConfigure your project `settings.py` like this\n\n```py\nINSTALLED_APPS = [\n    # ...\n    \"rest_framework\",\n    \"drf_spectacular\",\n    # ...\n]\n\nREST_FRAMEWORK = {\n    \"DEFAULT_SCHEMA_CLASS\": \"drf_spectacular.openapi.AutoSchema\",\n}\n\nSPECTACULAR_SETTINGS = {\n    \"TITLE\": \"Your Project API\",\n    \"DESCRIPTION\": \"Your project description\",\n    \"VERSION\": \"1.0.0\",\n    \"SERVE_INCLUDE_SCHEMA\": False,\n    'SCHEMA_PATH_PREFIX': '/api',\n}\n```\n\n## Usage\n\nserializers.py\n\n```python\nfrom django.contrib.auth.models import User\nfrom rest_framework import serializers\n\n\nclass UserOut(serializers.ModelSerializer):\n    class Meta:\n        model = User\n        fields = [\"id\", \"username\"]\n\n\nclass SquareOut(serializers.Serializer):\n    result = serializers.IntegerField()\n\n\nclass SquareQuery(serializers.Serializer):\n    n = serializers.IntegerField(default=2)\n```\n\nviews.py\n\n```python\nfrom typing import Any\n\nfrom django.contrib.auth.models import User\nfrom rest_framework.decorators import action\nfrom rest_framework.mixins import ListModelMixin, RetrieveModelMixin\nfrom rest_framework.permissions import IsAdminUser, IsAuthenticated\nfrom rest_framework.viewsets import GenericViewSet\n\nfrom drf_apischema import ASRequest, apischema, apischema_view\n\nfrom .serializers import SquareOut, SquareQuery, UserOut\n\n# Create your views here.\n\n\n@apischema_view(\n    retrieve=apischema(summary=\"Retrieve a user\"),\n)\nclass UserViewSet(GenericViewSet, ListModelMixin, RetrieveModelMixin):\n    \"\"\"User management\"\"\"\n\n    queryset = User.objects.all()\n    serializer_class = UserOut\n    permission_classes = [IsAuthenticated]\n\n    # Define a view that requires permissions\n    @apischema(permissions=[IsAdminUser])\n    def list(self, request):\n        \"\"\"List all\n\n        Document here\n        xxx\n        \"\"\"\n        return super().list(request)\n\n    # will auto wrap it with `apischema` in `apischema_view`\n    @action(methods=[\"post\"], detail=True)\n    def echo(self, request, pk):\n        \"\"\"Echo the request\"\"\"\n        return self.get_serializer(self.get_object()).data\n\n    @apischema(query=SquareQuery, response=SquareOut)\n    @action(methods=[\"get\"], detail=False)\n    def square(self, request: ASRequest[SquareQuery]) -> Any:\n        \"\"\"The square of a number\"\"\"\n        # The request.serializer is an instance of SquareQuery that has been validated\n        # print(request.serializer)\n\n        # The request.validated_data is the validated data of the serializer\n        n: int = request.validated_data[\"n\"]\n\n        # Note that apischema won't automatically process the response with the declared response serializer,\n        # but it will wrap it with rest_framework.response.Response\n        # So you don't need to manually wrap it with Response\n        return SquareOut({\"result\": n * n}).data\n```\n\nurls.py\n\n```python\nfrom django.urls import include, path\nfrom rest_framework.routers import DefaultRouter\n\nfrom drf_apischema.urls import api_path\n\nfrom .views import *\n\nrouter = DefaultRouter()\nrouter.register(\"test\", TestViewSet, basename=\"test\")\n\n\nurlpatterns = [\n    # Auto-generate /api/schema/, /api/schema/swagger/ and /api/schema/redoc/ for documentation\n    api_path(\"api/\", [path(\"\", include(router.urls))])\n]\n```\n\n## settings\n\nsettings.py\n\n```python\nDRF_APISCHEMA_SETTINGS = {\n    # Enable transaction wrapping for APIs\n    \"TRANSACTION\": True,\n    # Enable SQL logging\n    \"SQL_LOGGING\": True,\n    # Indent SQL queries\n    \"SQL_LOGGING_REINDENT\": True,\n    # Use method docstring as summary and description\n    \"SUMMARY_FROM_DOC\": True,\n    # Show permissions in description\n    \"SHOW_PERMISSIONS\": True,\n    # If True, request_body and response will be empty by default if the view is action decorated\n    \"ACTION_DEFAULTS_EMPTY\": True,\n}\n```\n\n## drf-yasg version\n\nSee branch drf-yasg, it is not longer supported\n\n## Troubleshooting\n\n### Doesn't showed permissions description of `permission_classes`\n\nWrap the view with `apischema_view`.\n\n```python\n@apischema_view()\nclass XxxViewSet(GenericViewSet):\n    permissions_classes = [IsAuthenticated]\n```\n\n### TypeError: cannot be assigned to parameter of type \"_View@action\"\n\nJust annotate the return type to `Any`, as `apischema` will wrap it with `Response`.\n\n```python\n@apischema()\n@action(methods=[\"get\"], detail=False)\ndef xxx(self, request) -> Any:\n    ...\n```\n",
    "bugtrack_url": null,
    "license": "BSD 3-Clause License  Copyright (c) 2025, Hmeqo  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
    "summary": "API schema generator and validator for Django REST framework",
    "version": "0.2.9",
    "project_urls": {
        "Issues": "https://github.com/hmeqo/drf-apischema/issues",
        "Repository": "https://github.com/hmeqo/drf-apischema.git"
    },
    "split_keywords": [
        "django",
        " django-rest-framework",
        " documentation",
        " drf",
        " drf-apischema",
        " drf-spectacular",
        " openapi",
        " schema",
        " swagger"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "b1920c58f95a1c4a5505f0dafe23ecfbc1d8ee1b946febf1e419d2f900b76861",
                "md5": "532f2dc1ab258111136b94f40b437910",
                "sha256": "89e081f2231cd0b3829708614e2a234fedb821ab2a585c119cf20aeae930391c"
            },
            "downloads": -1,
            "filename": "drf_apischema-0.2.9-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "532f2dc1ab258111136b94f40b437910",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 13123,
            "upload_time": "2025-10-07T07:42:48",
            "upload_time_iso_8601": "2025-10-07T07:42:48.757198Z",
            "url": "https://files.pythonhosted.org/packages/b1/92/0c58f95a1c4a5505f0dafe23ecfbc1d8ee1b946febf1e419d2f900b76861/drf_apischema-0.2.9-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "ab22e2219948061fb8f01cfbc4e6fc918289c516791426ec845734d9dfc86c24",
                "md5": "3df6751bcc3609074c73d12c231da395",
                "sha256": "a3953fbb99135b66ed6989d39f446704dd1e389ce36d30a166961d78a09a8296"
            },
            "downloads": -1,
            "filename": "drf_apischema-0.2.9.tar.gz",
            "has_sig": false,
            "md5_digest": "3df6751bcc3609074c73d12c231da395",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 39246,
            "upload_time": "2025-10-07T07:42:50",
            "upload_time_iso_8601": "2025-10-07T07:42:50.418833Z",
            "url": "https://files.pythonhosted.org/packages/ab/22/e2219948061fb8f01cfbc4e6fc918289c516791426ec845734d9dfc86c24/drf_apischema-0.2.9.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-07 07:42:50",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "hmeqo",
    "github_project": "drf-apischema",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "drf-apischema"
}
        
Elapsed time: 2.22108s