sanic-openapi-ext


Namesanic-openapi-ext JSON
Version 0.1.0 PyPI version JSON
download
home_pagehttps://pypi.org/project/sanic-openapi-ext/
SummarySanic OpenAPI extension offers an enhanced and convenient way to generate OpenAPI (Swagger) documentation from Marshmallow schemas
upload_time2024-02-18 22:16:05
maintainer
docs_urlNone
authorYurii Havrylko
requires_python>=3.8,<4.0
licenseMIT
keywords python sanic swagger marshmallow open-api sanic-ext
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # sanic-openapi-ext

**sanic-openapi-ext** is a Python package that provides a simplified method for generating OpenAPI (Swagger) documentation from Marshmallow schemas in a Sanic web application. It offers an explicit mapping between Marshmallow fields and OpenAPI fields, which aids in the automatic generation of precise API documentation.

## Features
- Automatic generation of OpenAPI (Swagger) documentation from Marshmallow schemas.
- Handles different types of Marshmallow fields including basic types, complex types, dates, and numbers.
- Supports conversion of nested fields and lists.

## Installation
```
pip install sanic-openapi-ext
```

## Quick Start
Here's a simple example of how to use sanic-openapi-ext:

```python
from marshmallow import Schema, fields
from sanic_openapi_ext import open_api_schemas

class UserSchema(Schema):
    name = fields.Str()
    birthdate = fields.Date()

# Generate OpenAPI schema from Marshmallow schema
user_openapi_schema = open_api_schemas(UserSchema())
```

## Examples
#### Input/output simple schema object

Parameter represents query params as `ExampleSchema`

Response represents json output as `ExampleSchema`

```python
from marshmallow import Schema, fields
from sanic import Sanic, response
from sanic_openapi_ext import open_api_schemas, open_api_schemas_params
from sanic_ext import openapi
from sanic_ext.extensions.openapi.definitions import Response


class ExampleSchema(Schema):
    name = fields.Str(required=True)
    age = fields.Integer(required=True)


app = Sanic("MyHelloWorldApp")


@app.get("/")
@openapi.definition(
    parameter=open_api_schemas_params(ExampleSchema()),
    response=[
        Response(open_api_schemas(ExampleSchema(), is_json=True), status=200),
    ],
)
async def get_and_return_example_schema(request):
    result = ExampleSchema().dump({"name": "John Doe", "age": 42})
    return response.json({"success": 200, "result": result})

```
![Sanic OpenAPI spec screenshot](https://i.imgur.com/dTI0DLb.png)


#### Input schema object with enum, output - nested schema with enum

Parameter represents header params as `ExampleSchema`

Response represents json output as list of `ExampleSchema`

```python
from enum import Enum
from marshmallow import Schema, fields
from sanic import Sanic, response
from sanic_openapi_ext import open_api_schemas, open_api_schemas_params
from sanic_ext import openapi
from sanic_ext.extensions.openapi.definitions import Response


class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3


class ExampleSchema(Schema):
    text = fields.Str()
    color = fields.Enum(Color)


class ExampleListSchema(Schema):
    items = fields.List(fields.Nested(ExampleSchema))


app = Sanic("MyHelloWorldApp")


@app.get("/")
@openapi.definition(
    parameter=open_api_schemas_params(ExampleSchema(), location="header"),
    response=[
        Response(open_api_schemas(ExampleListSchema(), is_json=True), status=200),
    ],
)
async def get_and_return_example_schema(request):
    result = ExampleListSchema().dump([{"text": "Lorem ipsum", "color": 1}], many=True)
    return response.json({"success": 200, "result": result})
```
![Sanic OpenAPI spec screenshot](https://i.imgur.com/9HaTENf.png)

## Mapping reference
Below is a mapping table of how Marshmallow fields are converted into OpenAPI fields:

| Marshmallow Field | OpenAPI Field |
| ------------------ | ------------- |
| DateTime           | doc.DateTime |
| Date               | doc.Date |
| Time               | doc.Time |
| Integer,Int        | doc.Integer |
| Float              | doc.Float |
| Decimal            | doc.String |
| String, Str        | doc.String |
| Boolean, Bool      | doc.Boolean |
| Enum               | doc.Schema |
| List               | doc.Array |
| Nested             | doc.Object |

Note:

- If the `many` attribute of the Marshmallow schema is set to `True`, or if the input `many` attribute is `True`, a doc.List will be returned.
- If the input `is_json` attribute is `True`, a doc.JsonBody will be returned.
- If the field is of type `fields.Enum`, a `doc.Schema`, which accepts the enumeration, is returned.
- If the field is of type `fields.List`, the inner_field is accessed. If the inner_field is a `fields.Nested`, a `doc.Object` is returned with the properties of the nested schema. If the inner_fields belong to other types, a `doc.Array` is returned with the properties of the inner type.
- For fields not listed in the table, `doc.String` is used as a default.

Please, remember that this mapping may vary according to the use and the specific need of the project.

# Contribute
We'd love for you to contribute to our source code and to make **sanic-openapi-ext** even better than it is today! Here are some ways you can contribute:

- by reporting bugs
- by suggesting new features
- by writing or editing documentation
- by writing specifications
- by writing code (no patch is too small, fix typos, add comments, clean up inconsistent whitespace)
- by refactoring code
- by closing issues
- by reviewing patches

# License
sanic-openapi-ext is released under the MIT license.

            

Raw data

            {
    "_id": null,
    "home_page": "https://pypi.org/project/sanic-openapi-ext/",
    "name": "sanic-openapi-ext",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "python,sanic,swagger,marshmallow,open-api,sanic-ext",
    "author": "Yurii Havrylko",
    "author_email": "yurii.havrylko@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/90/60/a605f5af40a4dd119f3083d4e0dd567cfc6a29457fac983c80971299d0d3/sanic_openapi_ext-0.1.0.tar.gz",
    "platform": null,
    "description": "# sanic-openapi-ext\n\n**sanic-openapi-ext** is a Python package that provides a simplified method for generating OpenAPI (Swagger) documentation from Marshmallow schemas in a Sanic web application. It offers an explicit mapping between Marshmallow fields and OpenAPI fields, which aids in the automatic generation of precise API documentation.\n\n## Features\n- Automatic generation of OpenAPI (Swagger) documentation from Marshmallow schemas.\n- Handles different types of Marshmallow fields including basic types, complex types, dates, and numbers.\n- Supports conversion of nested fields and lists.\n\n## Installation\n```\npip install sanic-openapi-ext\n```\n\n## Quick Start\nHere's a simple example of how to use sanic-openapi-ext:\n\n```python\nfrom marshmallow import Schema, fields\nfrom sanic_openapi_ext import open_api_schemas\n\nclass UserSchema(Schema):\n    name = fields.Str()\n    birthdate = fields.Date()\n\n# Generate OpenAPI schema from Marshmallow schema\nuser_openapi_schema = open_api_schemas(UserSchema())\n```\n\n## Examples\n#### Input/output simple schema object\n\nParameter represents query params as `ExampleSchema`\n\nResponse represents json output as `ExampleSchema`\n\n```python\nfrom marshmallow import Schema, fields\nfrom sanic import Sanic, response\nfrom sanic_openapi_ext import open_api_schemas, open_api_schemas_params\nfrom sanic_ext import openapi\nfrom sanic_ext.extensions.openapi.definitions import Response\n\n\nclass ExampleSchema(Schema):\n    name = fields.Str(required=True)\n    age = fields.Integer(required=True)\n\n\napp = Sanic(\"MyHelloWorldApp\")\n\n\n@app.get(\"/\")\n@openapi.definition(\n    parameter=open_api_schemas_params(ExampleSchema()),\n    response=[\n        Response(open_api_schemas(ExampleSchema(), is_json=True), status=200),\n    ],\n)\nasync def get_and_return_example_schema(request):\n    result = ExampleSchema().dump({\"name\": \"John Doe\", \"age\": 42})\n    return response.json({\"success\": 200, \"result\": result})\n\n```\n![Sanic OpenAPI spec screenshot](https://i.imgur.com/dTI0DLb.png)\n\n\n#### Input schema object with enum, output - nested schema with enum\n\nParameter represents header params as `ExampleSchema`\n\nResponse represents json output as list of `ExampleSchema`\n\n```python\nfrom enum import Enum\nfrom marshmallow import Schema, fields\nfrom sanic import Sanic, response\nfrom sanic_openapi_ext import open_api_schemas, open_api_schemas_params\nfrom sanic_ext import openapi\nfrom sanic_ext.extensions.openapi.definitions import Response\n\n\nclass Color(Enum):\n    RED = 1\n    GREEN = 2\n    BLUE = 3\n\n\nclass ExampleSchema(Schema):\n    text = fields.Str()\n    color = fields.Enum(Color)\n\n\nclass ExampleListSchema(Schema):\n    items = fields.List(fields.Nested(ExampleSchema))\n\n\napp = Sanic(\"MyHelloWorldApp\")\n\n\n@app.get(\"/\")\n@openapi.definition(\n    parameter=open_api_schemas_params(ExampleSchema(), location=\"header\"),\n    response=[\n        Response(open_api_schemas(ExampleListSchema(), is_json=True), status=200),\n    ],\n)\nasync def get_and_return_example_schema(request):\n    result = ExampleListSchema().dump([{\"text\": \"Lorem ipsum\", \"color\": 1}], many=True)\n    return response.json({\"success\": 200, \"result\": result})\n```\n![Sanic OpenAPI spec screenshot](https://i.imgur.com/9HaTENf.png)\n\n## Mapping reference\nBelow is a mapping table of how Marshmallow fields are converted into OpenAPI fields:\n\n| Marshmallow Field | OpenAPI Field |\n| ------------------ | ------------- |\n| DateTime           | doc.DateTime |\n| Date               | doc.Date |\n| Time               | doc.Time |\n| Integer,Int        | doc.Integer |\n| Float              | doc.Float |\n| Decimal            | doc.String |\n| String, Str        | doc.String |\n| Boolean, Bool      | doc.Boolean |\n| Enum               | doc.Schema |\n| List               | doc.Array |\n| Nested             | doc.Object |\n\nNote:\n\n- If the `many` attribute of the Marshmallow schema is set to `True`, or if the input `many` attribute is `True`, a doc.List will be returned.\n- If the input `is_json` attribute is `True`, a doc.JsonBody will be returned.\n- If the field is of type `fields.Enum`, a `doc.Schema`, which accepts the enumeration, is returned.\n- If the field is of type `fields.List`, the inner_field is accessed. If the inner_field is a `fields.Nested`, a `doc.Object` is returned with the properties of the nested schema. If the inner_fields belong to other types, a `doc.Array` is returned with the properties of the inner type.\n- For fields not listed in the table, `doc.String` is used as a default.\n\nPlease, remember that this mapping may vary according to the use and the specific need of the project.\n\n# Contribute\nWe'd love for you to contribute to our source code and to make **sanic-openapi-ext** even better than it is today! Here are some ways you can contribute:\n\n- by reporting bugs\n- by suggesting new features\n- by writing or editing documentation\n- by writing specifications\n- by writing code (no patch is too small, fix typos, add comments, clean up inconsistent whitespace)\n- by refactoring code\n- by closing issues\n- by reviewing patches\n\n# License\nsanic-openapi-ext is released under the MIT license.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Sanic OpenAPI extension offers an enhanced and convenient way to generate OpenAPI (Swagger) documentation from Marshmallow schemas",
    "version": "0.1.0",
    "project_urls": {
        "Documentation": "https://github.com/yuriihavrylko/sanic_openapi_ext/blob/master/README.md",
        "Homepage": "https://pypi.org/project/sanic-openapi-ext/",
        "Repository": "https://github.com/yuriihavrylko/sanic_openapi_ext"
    },
    "split_keywords": [
        "python",
        "sanic",
        "swagger",
        "marshmallow",
        "open-api",
        "sanic-ext"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cd70e6587b76c90e012173c5be0968a716385afd3b062842d85b484096a50fb3",
                "md5": "2bb1d5418d9d40f7f5de34f236b38127",
                "sha256": "667447311190db835d92116bc4975862e184a09f5588597dfdbc64c998b9e2c5"
            },
            "downloads": -1,
            "filename": "sanic_openapi_ext-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2bb1d5418d9d40f7f5de34f236b38127",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 5605,
            "upload_time": "2024-02-18T22:16:03",
            "upload_time_iso_8601": "2024-02-18T22:16:03.668515Z",
            "url": "https://files.pythonhosted.org/packages/cd/70/e6587b76c90e012173c5be0968a716385afd3b062842d85b484096a50fb3/sanic_openapi_ext-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9060a605f5af40a4dd119f3083d4e0dd567cfc6a29457fac983c80971299d0d3",
                "md5": "1f9b387b7b12ba69d95cf408ceb74432",
                "sha256": "5d177db3d5c4dc5fb45678428620f0fa82f8acc96f095e1c0922b9d854285f88"
            },
            "downloads": -1,
            "filename": "sanic_openapi_ext-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "1f9b387b7b12ba69d95cf408ceb74432",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 4737,
            "upload_time": "2024-02-18T22:16:05",
            "upload_time_iso_8601": "2024-02-18T22:16:05.561367Z",
            "url": "https://files.pythonhosted.org/packages/90/60/a605f5af40a4dd119f3083d4e0dd567cfc6a29457fac983c80971299d0d3/sanic_openapi_ext-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-18 22:16:05",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "yuriihavrylko",
    "github_project": "sanic_openapi_ext",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "sanic-openapi-ext"
}
        
Elapsed time: 3.58451s