mozilla

Quickstart

Installing

You may install us with pip:

$ pip install cornice_swagger

From an existing Cornice application, you may add this extension to your Pyramid configurator after including cornice:

from pyramid.config import Configurator

def setup():
    config = Configurator()
    config.include('cornice')
    config.include('cornice_swagger')

You can than create your OpenAPI/Swagger JSON using:

from cornice_swagger import CorniceSwagger
from cornice.service import get_services

my_generator = CorniceSwagger(get_services())
my_spec = my_generator('MyAPI', '1.0.0')

Alternatively you can use a directive to set up OpenAPI/Swagger JSON and serve API explorer on your application:

config = Configurator()
config.include('cornice')
config.include('cornice_swagger')
config.cornice_enable_openapi_view(
    api_path='/api-explorer/swagger.json',
    title='MyAPI',
    description="OpenAPI documentation",
    version='1.0.0'
)
config.cornice_enable_openapi_explorer(
    api_explorer_path='/api-explorer')

Then you will be able to access Swagger UI API explorer on url:

http://localhost:8000/api-explorer (in the example above)

Using a scaffold

If you want to start a new project, there is a cookiecutter scaffold that can be used:

$ cookiecutter https://github.com/delijati/cookiecutter-cornice_swagger.git
$ cd demo
$ pip install -e .
$ cd demo/static
$ bower install

Show me a minimalist useful example

import colander
from cornice import Service
from cornice.validators import colander_body_validator
from wsgiref.simple_server import make_server
from pyramid.config import Configurator


_VALUES = {}


# Create a simple service that will store and retrieve values
values = Service(name='foo',
                 path='/values/{key}',
                 description="Cornice Demo")


# Create a body schema for our requests
class BodySchema(colander.MappingSchema):
    value = colander.SchemaNode(colander.String(),
                                description='My precious value')


# Create a response schema for our 200 responses
class OkResponseSchema(colander.MappingSchema):
    body = BodySchema()


# Aggregate the response schemas for get requests
response_schemas = {
    '200': OkResponseSchema(description='Return value')
}


# Create our cornice service views
class MyValueApi(object):
    """My precious API."""

    @values.get(tags=['values'], response_schemas=response_schemas)
    def get_value(request):
        """Returns the value."""
        key = request.matchdict['key']
        return _VALUES.get(key)

    @values.put(tags=['values'], validators=(colander_body_validator, ),
                schema=BodySchema(), response_schemas=response_schemas)
    def set_value(request):
        """Set the value and returns *True* or *False*."""

        key = request.matchdict['key']
        _VALUES[key] = request.json_body
        return _VALUES.get(key)


# Setup and run our app
def setup():
    config = Configurator()
    config.include('cornice')
    config.include('cornice_swagger')
    # Create views to serve our OpenAPI spec
    config.cornice_enable_openapi_view(
        api_path='/__api__',
        title='MyAPI',
        description="OpenAPI documentation",
        version='1.0.0'
    )
    # Create views to serve OpenAPI spec UI explorer
    config.cornice_enable_openapi_explorer(api_explorer_path='/api-explorer')
    config.scan()
    app = config.make_wsgi_app()
    return app


if __name__ == '__main__':
    app = setup()
    server = make_server('127.0.0.1', 8000, app)
    print('Visit me on http://127.0.0.1:8000')
    print('''You can see the API explorer here:
    http://127.0.0.1:8000/api-explorer''')
    server.serve_forever()

The resulting swagger.json at http://localhost:8000/__api__ is:

{
    "swagger": "2.0",
    "info": {
        "version": "1.0.0",
        "title": "MyAPI"
    },
    "basePath": "/",
    "tags": [
        {
            "name": "values"
        }
    ]
    "paths": {
        "/values/{key}": {
            "parameters": [
                {
                    "name": "value",
                    "in": "path",
                    "required": true,
                    "type": "string"
                }
            ],
            "get": {
                "tags": [
                    "values"
                ],
                "responses": {
                    "200": {
                        "description": "Return value",
                        "schema": {
                            "required": [
                                "value"
                            ],
                            "type": "object",
                            "properties": {
                                "value": {
                                    "type": "string",
                                    "description": "My precious value",
                                    "title": "Value"
                                }
                            },
                            "title": "BodySchema"
                        }
                    }

                },
                "produces": [
                    "application/json"
                ]
            },
            "put": {
                "tags": [
                    "values"
                ],
                "parameters": [
                    {
                        "name": "PutBodySchema",
                        "in": "body",
                        "schema": {
                            "required": [
                                "value"
                            ],
                            "type": "object",
                            "properties": {
                                "value": {
                                    "type": "string",
                                    "description": "My precious value",
                                    "title": "Value"
                                }
                            },
                            "title": "PutBodySchema"
                        },
                        "required": true
                    }
                ],
                "produces": [
                    "application/json"
                ],
                "responses": {
                    "200": {
                        "description": "Return value",
                        "schema": {
                            "required": [
                                "value"
                            ],
                            "type": "object",
                            "properties": {
                                "value": {
                                    "type": "string",
                                    "description": "My precious value",
                                    "title": "Value"
                                }
                            },
                            "title": "BodySchema"
                        }
                    }
                }
            }
        },
        "/__api__": {
            "get": {
                "responses": {
                    "default": {
                        "description": "UNDOCUMENTED RESPONSE"
                    }
                },
                "produces": [
                    "application/json"
                ]
            }
        }
    }
}