drf-apischema


Namedrf-apischema JSON
Version 0.1.15 PyPI version JSON
download
home_pageNone
SummaryAPI schema generator and validator for Django REST framework
upload_time2025-01-10 21:44:01
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseMIT 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.
keywords config dotfiles
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ## Introduction

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.

## 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
```

## Usage

views.py

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

from drf_apischema import ASRequest, apischema

from .serializers import SquareOut, SquareQuery, TestOut


class TestViewSet(GenericViewSet):
    serializer_class = TestOut

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

        Document here
        xxx
        """
        # We don't process the response using the declared serializer
        # but instead wrap it with rest_framework.response.Response
        return self.get_serializer([1, 2, 3]).data

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

        # request.validated_data is serializer.validated_data
        n: int = request.validated_data["n"]
        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/swagger/ and /api/redoc/ for documentation
    api_path("api/", [path("", include(router.urls))])
]
```

## settings

settings.py

```python
DRF_APISCHEMA_SETTINGS = {
    # wrap method in a transaction
    "TRANSACTION": True,
    # log SQL queries in debug mode
    "SQL_LOGGER": True,
    # indent SQL queries
    "SQL_LOGGER_REINDENT": True,
    # override default swagger auto schema
    "OVERRIDE_SWAGGER_AUTO_SCHEMA": True,
}
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "drf-apischema",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "config, dotfiles",
    "author": null,
    "author_email": "hmeqo <hmeqo@qq.com>",
    "download_url": "https://files.pythonhosted.org/packages/cb/3d/c48f90af22718acc0f330ef213fe628dbd6505713941e1b121cba7601940/drf_apischema-0.1.15.tar.gz",
    "platform": null,
    "description": "## Introduction\n\nAutomatically 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## 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    \"drf_yasg\",\n    \"rest_framework\",\n    # ...\n]\n\nSTATIC_URL = \"static/\"\n\n# Ensure you have been defined it\nSTATIC_ROOT = BASE_DIR / \"static\"\n\n# STATICFILES_DIRS = []\n```\n\nRun `collectstatic`\n\n```bash\npython manage.py collectstatic --noinput\n```\n\n## Usage\n\nviews.py\n\n```python\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import IsAdminUser\nfrom rest_framework.viewsets import GenericViewSet\n\nfrom drf_apischema import ASRequest, apischema\n\nfrom .serializers import SquareOut, SquareQuery, TestOut\n\n\nclass TestViewSet(GenericViewSet):\n    serializer_class = TestOut\n\n    # Define a view that requires permissions\n    @apischema(permissions=[IsAdminUser])\n    def list(self, request):\n        \"\"\"List all users\n\n        Document here\n        xxx\n        \"\"\"\n        # We don't process the response using the declared serializer\n        # but instead wrap it with rest_framework.response.Response\n        return self.get_serializer([1, 2, 3]).data\n\n    @action(methods=[\"GET\"], detail=False)\n    @apischema(query=SquareQuery, response=SquareOut, transaction=False)\n    def square(self, request: ASRequest[SquareQuery]):\n        \"\"\"Square a number\"\"\"\n        # request.serializer is instance of BQuery that is validated\n        # print(request.serializer)\n\n        # request.validated_data is serializer.validated_data\n        n: int = request.validated_data[\"n\"]\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/swagger/ and /api/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    # wrap method in a transaction\n    \"TRANSACTION\": True,\n    # log SQL queries in debug mode\n    \"SQL_LOGGER\": True,\n    # indent SQL queries\n    \"SQL_LOGGER_REINDENT\": True,\n    # override default swagger auto schema\n    \"OVERRIDE_SWAGGER_AUTO_SCHEMA\": True,\n}\n```\n",
    "bugtrack_url": null,
    "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.",
    "summary": "API schema generator and validator for Django REST framework",
    "version": "0.1.15",
    "project_urls": {
        "Issues": "https://github.com/hmeqo/drf-apischema/issues",
        "Repository": "https://github.com/hmeqo/drf-apischema.git"
    },
    "split_keywords": [
        "config",
        " dotfiles"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "92310de24cbdb4b441bbec92aef48ad8c7d4ec7ad9be8d89f4d9b4422d3813f6",
                "md5": "acbb1809079936f2a7583624c8c8b878",
                "sha256": "20cd4af1d39b948f215802a173713f03d0ca701eae9714b3c276535d83237c2d"
            },
            "downloads": -1,
            "filename": "drf_apischema-0.1.15-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "acbb1809079936f2a7583624c8c8b878",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 11711,
            "upload_time": "2025-01-10T21:43:58",
            "upload_time_iso_8601": "2025-01-10T21:43:58.276095Z",
            "url": "https://files.pythonhosted.org/packages/92/31/0de24cbdb4b441bbec92aef48ad8c7d4ec7ad9be8d89f4d9b4422d3813f6/drf_apischema-0.1.15-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "cb3dc48f90af22718acc0f330ef213fe628dbd6505713941e1b121cba7601940",
                "md5": "5fcb8fb86479e2fc421e2073004eee66",
                "sha256": "ea34f844864ebfe08a85ca991f0f0aee38490f3be50e236e55baaac5d1d9c7d8"
            },
            "downloads": -1,
            "filename": "drf_apischema-0.1.15.tar.gz",
            "has_sig": false,
            "md5_digest": "5fcb8fb86479e2fc421e2073004eee66",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 32138,
            "upload_time": "2025-01-10T21:44:01",
            "upload_time_iso_8601": "2025-01-10T21:44:01.134944Z",
            "url": "https://files.pythonhosted.org/packages/cb/3d/c48f90af22718acc0f330ef213fe628dbd6505713941e1b121cba7601940/drf_apischema-0.1.15.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-10 21:44:01",
    "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: 0.44331s