chocs-middleware-openapi


Namechocs-middleware-openapi JSON
Version 1.2.4 PyPI version JSON
download
home_pagehttps://github.com/kodemore/chocs-openapi
SummaryMiddleware to validate incoming requests with openapi spec.
upload_time2023-07-24 13:48:34
maintainer
docs_urlNone
authorDawid Kraczkowski
requires_python>=3.8,<4.0
licenseMIT
keywords openapi json-schema chocs http middleware
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Chocs-OpenApi <br> [![PyPI version](https://badge.fury.io/py/chocs-middleware.openapi.svg)](https://pypi.org/project/chocs-middleware.openapi/) [![CI](https://github.com/kodemore/chocs-openapi/actions/workflows/main.yaml/badge.svg)](https://github.com/kodemore/chocs-openapi/actions/workflows/main.yaml) [![Release](https://github.com/kodemore/chocs-openapi/actions/workflows/release.yml/badge.svg)](https://github.com/kodemore/chocs-openapi/actions/workflows/release.yml) [![codecov](https://codecov.io/gh/kodemore/chocs-openapi/branch/main/graph/badge.svg?token=GWMTNY5G0N)](https://codecov.io/gh/kodemore/chocs-openapi) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
OpenApi middleware for chocs library.

Newest OpenAPI Specification (v.3.x) can be easily integrated into Chocs through application's middleware. 
Validation is performed via [JsonSchema Draft-7.0 specification](https://json-schema.org) and all commonly 
used features are supported.

## Features

Open api integration can be used to:
- validate request's body
- validate request's path parameters
- validate request's headers
- validate request's query parameters
- validate request's cookies  
- generate dtos from openapi file

## Installation

With pip,
```shell
pip install chocs-middleware.openapi
```
or through poetry
```shell
poetry add chocs-middleware.openapi
```

# Usage

## Using your OpenAPI file

Chocs can read json and yaml files, this example will cover yaml usage although the only difference is the file extension.

```python
import chocs
from chocs_middleware.openapi import OpenApiMiddleware
from os import path

# absolute path to file containing open api documentation; yaml and json files are supported
openapi_filename = path.join(path.dirname(__file__), "/openapi.yml")

# instantiating application and passing open api middleware
app = chocs.Application(OpenApiMiddleware(openapi_filename, validate_body=True, validate_query=True))

# the registered route must correspond to open api route within `path` section.
# if request body is invalid the registered controller will not be invoked
@app.post("/pets")
def create_pet(request: chocs.HttpRequest) -> chocs.HttpResponse:
  ...
  return chocs.HttpResponse(status=200)
```
Complete integration example can be [found here](./examples/input_validation_with_open_api/openapi.yml)

> Keep in mind registered route has to match 1:1 the specified route inside `paths` section inside your OpenApi documentation

## Validating request body

Below is very simple schema to validate request body of a `POST /pet` request. Request body is required, should be valid json request and contain the following properties:
- name (string)
- tags (array of string)
- id (optional string)

`openapi.yml`
```yaml
openapi: "3.0.0"
info:
  version: "1.0.0"
  title: "Pet Store"
paths:
  /pets:
    post:
      description: Creates a new Pet
      requestBody:
        description: Pet
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Pet"
      responses:
        200:
          description: "Success"
components:
  schemas:
    Pet:
      type: object
      required:
        - name
        - tag
      properties:
        id:
          type: integer
        name:
          type: string
        tag:
          type: array
          items:
            type: string
```

`app.py`
```python
import chocs
from chocs_middleware.openapi import OpenApiMiddleware
from os import path

openapi_filename = path.join(path.dirname(__file__), "/openapi.yml")
app = chocs.Application(OpenApiMiddleware(openapi_filename, validate_body=True))

@app.post("/pets")
def create_pet(request: chocs.HttpRequest) -> chocs.HttpResponse:
  pet = request.parsed_body # here we will get valid pet
  return chocs.HttpResponse(status=200)

chocs.serve(app)
```

`create_pet` controller will be only invoked if request contains valid body. Pet's data can be accessed through `request.parsed_body` which is a dict-like object.

## Json schema support

Chocs uses JSON Schema to validate your open api definitions with full draft-7 support and almost complete 2019-09 standard support. 
This means you can use almost every feature described on the [understanding json schema](https://json-schema.org/understanding-json-schema/reference/index.html) webpage. 
The webpage is a great resource full of examples and detailed descriptions around JSON Schema. 


> There are some caveats around `allOf` validator:
> - all object schemas inside `allOf` definition are automatically composed into a single object definition
> - when combining string validators make sure format validator is the last validator in the pipeline otherwise validation might fail due to string casting


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/kodemore/chocs-openapi",
    "name": "chocs-middleware-openapi",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "openapi,json-schema,chocs,http,middleware",
    "author": "Dawid Kraczkowski",
    "author_email": "dawid.kraczkowski@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/6e/03/5775daeda5c24b1b01d5a8f34e83780a154a5d769cc2b868e6d98729d01f/chocs_middleware_openapi-1.2.4.tar.gz",
    "platform": null,
    "description": "# Chocs-OpenApi <br> [![PyPI version](https://badge.fury.io/py/chocs-middleware.openapi.svg)](https://pypi.org/project/chocs-middleware.openapi/) [![CI](https://github.com/kodemore/chocs-openapi/actions/workflows/main.yaml/badge.svg)](https://github.com/kodemore/chocs-openapi/actions/workflows/main.yaml) [![Release](https://github.com/kodemore/chocs-openapi/actions/workflows/release.yml/badge.svg)](https://github.com/kodemore/chocs-openapi/actions/workflows/release.yml) [![codecov](https://codecov.io/gh/kodemore/chocs-openapi/branch/main/graph/badge.svg?token=GWMTNY5G0N)](https://codecov.io/gh/kodemore/chocs-openapi) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\nOpenApi middleware for chocs library.\n\nNewest OpenAPI Specification (v.3.x) can be easily integrated into Chocs through application's middleware. \nValidation is performed via [JsonSchema Draft-7.0 specification](https://json-schema.org) and all commonly \nused features are supported.\n\n## Features\n\nOpen api integration can be used to:\n- validate request's body\n- validate request's path parameters\n- validate request's headers\n- validate request's query parameters\n- validate request's cookies  \n- generate dtos from openapi file\n\n## Installation\n\nWith pip,\n```shell\npip install chocs-middleware.openapi\n```\nor through poetry\n```shell\npoetry add chocs-middleware.openapi\n```\n\n# Usage\n\n## Using your OpenAPI file\n\nChocs can read json and yaml files, this example will cover yaml usage although the only difference is the file extension.\n\n```python\nimport chocs\nfrom chocs_middleware.openapi import OpenApiMiddleware\nfrom os import path\n\n# absolute path to file containing open api documentation; yaml and json files are supported\nopenapi_filename = path.join(path.dirname(__file__), \"/openapi.yml\")\n\n# instantiating application and passing open api middleware\napp = chocs.Application(OpenApiMiddleware(openapi_filename, validate_body=True, validate_query=True))\n\n# the registered route must correspond to open api route within `path` section.\n# if request body is invalid the registered controller will not be invoked\n@app.post(\"/pets\")\ndef create_pet(request: chocs.HttpRequest) -> chocs.HttpResponse:\n  ...\n  return chocs.HttpResponse(status=200)\n```\nComplete integration example can be [found here](./examples/input_validation_with_open_api/openapi.yml)\n\n> Keep in mind registered route has to match 1:1 the specified route inside `paths` section inside your OpenApi documentation\n\n## Validating request body\n\nBelow is very simple schema to validate request body of a `POST /pet` request. Request body is required, should be valid json request and contain the following properties:\n- name (string)\n- tags (array of string)\n- id (optional string)\n\n`openapi.yml`\n```yaml\nopenapi: \"3.0.0\"\ninfo:\n  version: \"1.0.0\"\n  title: \"Pet Store\"\npaths:\n  /pets:\n    post:\n      description: Creates a new Pet\n      requestBody:\n        description: Pet\n        required: true\n        content:\n          application/json:\n            schema:\n              $ref: \"#/components/schemas/Pet\"\n      responses:\n        200:\n          description: \"Success\"\ncomponents:\n  schemas:\n    Pet:\n      type: object\n      required:\n        - name\n        - tag\n      properties:\n        id:\n          type: integer\n        name:\n          type: string\n        tag:\n          type: array\n          items:\n            type: string\n```\n\n`app.py`\n```python\nimport chocs\nfrom chocs_middleware.openapi import OpenApiMiddleware\nfrom os import path\n\nopenapi_filename = path.join(path.dirname(__file__), \"/openapi.yml\")\napp = chocs.Application(OpenApiMiddleware(openapi_filename, validate_body=True))\n\n@app.post(\"/pets\")\ndef create_pet(request: chocs.HttpRequest) -> chocs.HttpResponse:\n  pet = request.parsed_body # here we will get valid pet\n  return chocs.HttpResponse(status=200)\n\nchocs.serve(app)\n```\n\n`create_pet` controller will be only invoked if request contains valid body. Pet's data can be accessed through `request.parsed_body` which is a dict-like object.\n\n## Json schema support\n\nChocs uses JSON Schema to validate your open api definitions with full draft-7 support and almost complete 2019-09 standard support. \nThis means you can use almost every feature described on the [understanding json schema](https://json-schema.org/understanding-json-schema/reference/index.html) webpage. \nThe webpage is a great resource full of examples and detailed descriptions around JSON Schema. \n\n\n> There are some caveats around `allOf` validator:\n> - all object schemas inside `allOf` definition are automatically composed into a single object definition\n> - when combining string validators make sure format validator is the last validator in the pipeline otherwise validation might fail due to string casting\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Middleware to validate incoming requests with openapi spec.",
    "version": "1.2.4",
    "project_urls": {
        "Documentation": "https://github.com/kodemore/chocs-openapi",
        "Homepage": "https://github.com/kodemore/chocs-openapi",
        "Repository": "https://github.com/kodemore/chocs-openapi"
    },
    "split_keywords": [
        "openapi",
        "json-schema",
        "chocs",
        "http",
        "middleware"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6e035775daeda5c24b1b01d5a8f34e83780a154a5d769cc2b868e6d98729d01f",
                "md5": "6f6324db531006d1ab7c96c94ad8d0f5",
                "sha256": "36f144d0e64609c6a5ed69116f9d47009960b2ad4c7b9ace3dc137986b03a29e"
            },
            "downloads": -1,
            "filename": "chocs_middleware_openapi-1.2.4.tar.gz",
            "has_sig": false,
            "md5_digest": "6f6324db531006d1ab7c96c94ad8d0f5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 5857,
            "upload_time": "2023-07-24T13:48:34",
            "upload_time_iso_8601": "2023-07-24T13:48:34.369359Z",
            "url": "https://files.pythonhosted.org/packages/6e/03/5775daeda5c24b1b01d5a8f34e83780a154a5d769cc2b868e6d98729d01f/chocs_middleware_openapi-1.2.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-24 13:48:34",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "kodemore",
    "github_project": "chocs-openapi",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "chocs-middleware-openapi"
}
        
Elapsed time: 0.22309s