API Reference

Generator

class cnctdocs.generators.ConnectSchemaGenerator(*args, **kwargs)

Generates an OpenAPI definitions file by inspecting the API endpoints.

Raises:

ImproperlyConfigured – If the DRF_CONNECT_DOCS setting is not present.

endpoint_inspector_cls

alias of EndpointEnumerator

get_schema(request)

Generates and returns the OpenAPI definitions.

Parameters:

request (django.http.HttpRequest) – A request object.

Returns:

The OpenAPI definitions.

Return type:

dict

Schema

class cnctdocs.generators.ConnectAutoSchema

Schema class that inspect views to generate OpenAPI schema definitions.

filter_inspector_cls

alias of FilterInspector

get_operation(path, method, pattern_name=None)

Returns the definitions for an api operation.

Parameters:
  • path (str) – The path to the api operation endpoint.

  • method (str) – The http method used to invoke the operation.

  • pattern_name (str, optional) – The name of the url pattern to prefix the operation name, defaults to None

Returns:

The operation definitions.

Return type:

dict

header_inspector_cls

alias of HeaderInspector

paginator_inspector_cls

alias of PaginatorInspector

parameter_inspector_cls

alias of ParameterInspector

response_inspector_cls

alias of ResponseInspector

serializer_inspector_cls

alias of SerializerInspector

set_registries(components_registry, tags_registry)

Set the components and tags registries to use to keep track of components and tags during the inspection.

Parameters:

Inspectors

Headers

class cnctdocs.inspectors.HeaderInspector(view, components_registry, msg_type='request')

Inspect a view to determine the headers definitions.

Parameters:
  • view (rest_framework.views.View) – The view to inspect.

  • components_registry (cnctdocs.registries.ComponentsRegistry) – The components registry to register headers components.

  • msg_type (str) – The type of the message being generated (request body or response body), defaults to ‘request’.

get_headers(action=None, method=None)

Returns the headers given an action or a method. The headers type (request or response) depends on the msg_type argument of the constructor.

Parameters:
  • action (str, optional) – The name of the action for which determine headers, defaults to None

  • method (str, optional) – The name of the method for which determine headers, defaults to None

Returns:

The headers definitions for the request or response.

Return type:

list,dict

Parameters

class cnctdocs.inspectors.ParameterInspector(view, components_registry)

Inspect a path to determine path parameters.

Parameters:
get_manual_parameters()

Returns manual path and/or querystring parameters.

Returns:

The list of manual path and/or querystring parameters.

Return type:

list

get_path_parameters(path)

Returns the path parameters definitions for a given path.

Parameters:

path (str) – The path to inspect.

Returns:

The path parameters schema definitions.

Return type:

list

Filters

class cnctdocs.inspectors.FilterInspector(view)

Inspect each filter backend to determine filters.

Parameters:

view (rest_framework.views.View) – The view to inspect.

Paginators

class cnctdocs.inspectors.PaginatorInspector(view, components_registry)

Inspect a view to determine pagination parameters and paginated response definitions.

Parameters:
get_paginated_response(schema)

Returns the definition of a paginated response given the response object schema definitions.

Returns:

The paginated response schema definitions.

Return type:

dict

get_paginator_parameters_references()

Add the pagination parameter definitions to the ComponentsRegistry and returns its reference.

Returns:

The $ref reference for the parameter.

Return type:

dict

Serializers

class cnctdocs.inspectors.SerializerInspector(view, components_registry, msg_type='request')

Inspect a serializer to determine the object definitions.

Parameters:
  • view (rest_framework.views.View) – The view to inspect.

  • components_registry (cnctdocs.registries.ComponentsRegistry) – The components registry to register parameters components.

  • msg_type (str) – The type of the message being generated (request body or response body), defaults to ‘request’.

get_object_reference()

Returns the object reference $ref for the object this serializer is for.

Returns:

The $ref reference.

Return type:

dict

exception cnctdocs.inspectors.IntrospectionImportError(serializer, method, nested_serializer)

Error class to notify import errors during introspection of SerializerMethodField or to_representation overrides.

Parameters:
  • serializer (rest_framework.serializers.Serializer) – The serializer being introspected.

  • method (str) – The name of the method referenced by the SerializerMethodField

  • nested_serializer (str) – The module dotted path to the serializer passed as the serializer argument of the @schema_method decorator.

exception cnctdocs.inspectors.IntrospectionInvokeError(serializer, method, callable_obj)

Error class to notify errors during introspection of SerializerMethodField or to_representation overrides. This error is thrown when the callable passed as the schema argument of the @schema_method decorator cannot be invoked.

Parameters:
  • serializer (rest_framework.serializers.Serializer) – The serializer being introspected.

  • method (str) – The name of the method referenced by the SerializerMethodField

  • callable_obj (callable) – The callable object.

Responses

class cnctdocs.inspectors.ResponseInspector(view, components_registry)

Inspect a view to determine “other” responses.

Parameters:
get_responses(action=None, method=None)

Returns the “other” responses given an action or a method.

Parameters:
  • action (str, optional) – The name of the action for which determine responses, defaults to None

  • method (str, optional) – The name of the method for which determine responses, defaults to None

Returns:

The responses definitions.

Return type:

dict

Registries

Tags

class cnctdocs.registries.TagsRegistry

Keep track of tags during the generation of the OpenAPI schema file.

add_tag(name, description=None, external_docs=None)

Add a tag to the registry if it is not already present.

Parameters:
  • name (str) – The name of the tag to be added.

  • description (str, optional) – The description of the tag, defaults to None

  • external_docs (str, optional) – An URL to external documentation, defaults to None

append(tags)

Append an array of tags in the form:

[
    {
        'name': '<name of the tag>',
        'description': '<description of the tag>',
        'externalDocs': { // optional
            'url': '<https://external.doc.server/external-doc-page>'
        }
    }
]

to the registry. See the tag object definition for more information.

if a tag already exists in the registry, it will not be added.

Parameters:

tags (list) – Array of tags.

exists(name)

Check if a tag is already present in the registry.

Parameters:

name (str) – The name of the tag to check if present

Returns:

True if the tag is present otherwise False.

Return type:

bool

get_tags()

Returns the tags node to include in the OpenAPI definitions file.

Returns:

the tags node.

Return type:

dict

classmethod load(tags)

Load tags from the tags node of a definition file and returns an instance of the registry.

Parameters:

tags (dict) – The tags node of a definition file.

Returns:

An instance of the registry filled with tags.

Return type:

TagsRegistry

Components

class cnctdocs.registries.ComponentsRegistry(models_qualifier='')

Keep track of reusable components (schemas, parameters, responses, etc) during the generation of the OpenAPI definitions.

Parameters:

models_qualifier (str, optional) – a prefix in dot notation to qualify models in order to avoid name conflicts, defaults to ‘’

add_parameter(name, definitions)

Add a parameter definition to the components node and return its $ref.

Parameters:
  • name (str) – Name for the parameter component.

  • definitions (dict) – The definitions of the parameter component.

Returns:

The reference to the parameter component ($ref).

Return type:

str

add_request_body(name, definitions)

Add a request body definition to the components node and return its $ref.

Parameters:
  • name (str) – Name for the request body component.

  • definitions (dict) – The definitions of the request body component.

Returns:

The reference to the request body component ($ref).

Return type:

str

add_response(name, definitions)

Add a response body definition to the components node and return its $ref.

Parameters:
  • name (str) – Name for the response body component.

  • definitions (dict) – the definitions of the response body component.

Returns:

The reference to the response body component ($ref).

Return type:

str

add_schema(name, definitions)

Add a schema definition to the components node and return its $ref.

Parameters:
  • name (str) – Name for the schema component.

  • definitions (dict) – the definitions of the schema component.

Returns:

The reference to the schema component ($ref).

Return type:

str

add_security_scheme(name, definitions)

Add a security scheme definition to the components node and return its $ref.

Parameters:
  • name (str) – Name for the security scheme component.

  • definitions (dict) – The definitions of the security scheme component.

Returns:

The reference to the security scheme component ($ref).

Return type:

str

append(components)

Append components to the registry. See the components object definition for more information.

if a component already exists in the registry, it will not be added.

Parameters:

components (dict) – A components’ node.

exists(name)

Check if a components is already in the registry. It can be checked by the component name of by its reference.

Parameters:

name (str) – name or reference to a component.

Returns:

True if the component exists, False otherwise.

Return type:

bool

get_components_definitions()

Returns the components node to include in the OpenAPI definition file.

Returns:

The components node.

Return type:

dict

classmethod load(components)

Load components from the components node of a definition file and returns an instance of the registry.

Parameters:

components (dict) – A components’ node.

Returns:

An instance of the registry filled with tags.

Return type:

TagsRegistry

Utilities

Decorator

@cnctdocs.utils.schema_method(serializer=None, field=None, schema=None, many=False)

Decorate a method of a SerializerMethodField or an ovveride of the to_representation method in order to define a schema.

Parameters:
  • serializer (rest_framework.serializers.Serializer or str, optional) – A serializer to inspect, defaults to None

  • field (rest_framework.serializers.Field, optional) – A field, defaults to None

  • schema (dict or callable, optional) – The definition of the returned object, defaults to None

  • many (bool, default to False) – Set to True if the returned object is an array.

Rendering

cnctdocs.utils.render(schema)

Render an OpenAPI schema definitions object as a yml file.

Parameters:

schema (dict) – The OpenAPI schema definitions.

Returns:

The yml rendered definitions file.

Return type:

str

Merging

cnctdocs.utils.merge_schemas(master_info, slaves_info)

Merges one or more slave schema definitions file into a master schema.

Parameters:
  • master (file) – A tuple with the master schema file and its name.

  • slaves (list) – A list of tuples with the slaves schema files and their names.

Raises:

MergeConflictError – If a component is already present.

Returns:

The merged definitions file.

Return type:

dict

exception cnctdocs.utils.MergeConflictError(filename, conflict_type, details)

Error class to track merge conflicts.

Parameters:
  • filename (str) – The file that generates the conflict.

  • conflict_type (str) – The type of conflict: _Components_.

  • details (str) – The conflict detail message.

Settings

Settings are configurable in settings.py by defining DRF_CONNECT_DOCS.

Example:

settings.py

DRF_CONNECT_DOCS = {
   'SCHEMA_INFO': {
      'title': 'Public API',
      'version': '1',
      'description': '**This is a description in markdown**',
   },
   ...
}

SCHEMA_INFO

The SCHEMA_INFO setting allow to customize the info object of the OpenAPI definitions.

Please refers to the OpenAPI 3 specifications for more details.

SCHEMA

The SCHEMA setting allow to add manual definitions to the generated file. It consists of the following sections:

servers

The servers section allow to list the api base url for each available environment (dev, staging, prod, etc). It defaults to an empty list.

Example:

'servers': [
   {
      'url': 'https://api.connect.cloudblue.com/public/v1',
      'name': 'Production',
      'description': 'This is the production server base url'
   },
],

Please read the **server object** documentation for more information.

security_schemes

It allow to specify a list of security schemes that the application supports. It defaults to an empty list.

Example:

'security_schemes': [
   {
      'type': 'apiKey',
      'in': 'header',
      'name': 'Authorization',
   },
],

Please read the security scheme object documentation for more information.

tags

It allow to define tags in order to groups views and their operations logically. In this section, it is possible to declare tags with its name, description and optional external documentation. It defaults to an empty list.

Example:

'tags': [
   {
         'name': 'Subscriptions',
         'description': 'Review, test and manage subscriptions of products '
                        'with the Subscriptions Management endpoints.',
   },
],

To add a view to a tag, you must specify the schema_tag attribute inside the view. Please refers to the Groups operations with tags section of the User guide for more information.

default_request_headers

Since there is no way to introspect views to determine request headers the application expect, they can be declared using the default_request_headers section in order to be added to each view. The headers declared in the default_request_headers can be overridden on a per-view basis. It defaults to an empty dictionary.

Example:

See Headers section of the User guide.

Please refers to the parameter object documentation for more information.

default_response_headers

Since there is no way to introspect views to determine response headers the application returns, they can be declared using the default_response_headers section in order to be added to each view. The headers declared in the default_response_headers can be overridden on a per-view basis. It defaults to an empty dictionary.

Example:

See Headers section of the User guide.

Please refers to the response object documentation for more information.

default_manual_parameters

Since there is no way to introspect views to determine all the path and querystring parameters, they can be declared using the default_manual_parameters section in order to be added to each view. The headers declared in the default_response_headers can be overridden on a per-view basis. It defaults to an empty list.

Example:

'default_manual_parameters': [
   {
      'name': 'my_param',
      'in': 'query',
      'required': True,
      'schema': {
            'type': 'string',
      },
   },
]

See Manual parameters section of the User guide.

Please refers to the parameter object documentation for more information.

default_responses

It’s possible to describe “other” responses and append them to each operation. It could be useful for example to describe a generic error response. The response declared through the default_responses can be overridden on a per-view basis. It defaults to an empty dictionary.

Example:

'default_responses': {
   '': { # You could limit this response to a specific action or http verb.
      '400': {
            'content': {
               'application/json': {
                  'schema': {
                        'type': 'object',
                        'properties': {
                           'error_code': {
                              'type': 'string',
                           },
                           'errors': {
                              'type': 'array',
                              'items': {
                                    'type': 'string',
                              },
                           },
                        },
                  },
               },
            },
            'description': 'this response will be appended to all operations.',
      },
   },
},

See Manual responses section of the User guide.

Please refers to the response object documentation for more information.

PREPEND_PATH

drf-connect-docs strips the common part from the set of paths. For example if paths are:

  • /public/api/v1/subscriptions/assets

  • /public/api/v1/subscriptions/assets/{pk}

the path part ‘/public/api/v1/subscriptions’ will be striped out so the specs paths looks like:

  • /assets

  • /assets/{pk}

The PREPEND_PATH setting allow to prepend a portion path.

For example if the want the path look like /myplatform/myservice/myendpoint so using:

DRF_CONNECT_DOCS = {
   'PREPEND_PATH': '/myplatform/myservice',
}

will do the job.

MODELS_QUALIFIER

Since drf-connect-docs has been developed with a microservice architecture in mind, often each microservice generates its own specification that will be merged togheter. To avoid models names collisions, you can add a qualifier to each object using the MODELS_QUALIFIER setting. For example, the devportal representation of an Asset could be different to the subscriptions one.

Using qualifiers, once merged the whole API definitions, the two different Asset objects will be:

...

subscriptions.Asset:
   properties:
      id:
         type: string
         readOnly: true

...

devportal.Asset:
   properties:
      id:
         type: integer
         readOnly: true

...

MODELS_QUALIFIER must be expressed with dot notation.

OUTPUT_SCHEMA_FILE

drf-connect-docs is shipped with a default view to serve the generated schema file through http(s). To work, you must set the OUTPUT_SCHEMA_FILE with the absolute path at which the schema file is located. It defaults to None, so if not set, the View returns a http status of 404.

SCHEMA_VIEW_AUTHENTICATION_CLASSES

By default, the View that serves the generate schema get its authentication classes from the rest framework DEFAULT_AUTHENTICATION_CLASSES setting. To customize the authentication classes for this view you can list your authentication classes using the SCHEMA_VIEW_AUTHENTICATION_CLASSES setting.

If you want to disable authentication for that view you can set the SCHEMA_VIEW_AUTHENTICATION_CLASSES to None.

The value can be a string, a list or a tuple.

SCHEMA_VIEW_PERMISSION_CLASSES

By default, the View that serves the generate schema get its permission classes from the rest framework DEFAULT_PERMISSION_CLASSES setting. To customize the permission classes for this view you can list your permissions classes using the SCHEMA_VIEW_PERMISSION_CLASSES setting.

If you want to disable permission checks for that view you can set the SCHEMA_VIEW_PERMISSION_CLASSES to None.

The value can be a string, a list or a tuple.

SCHEMA_VIEW_URL_PATH

The SCHEMA_VIEW_URL_PATH can be used to customize the tail part of the path at view the view is served. It defaults to specification.

Note

Please note that the url is declared using the django.urls.path function, so if you need to express your path through a regular expression, you have to import the view and configure the url yourself.

OUTPUT_SCHEMA_ON_START

The schema file could be generated using the management command generate_schema. But it could also be generated when the application starts. It defaults to True but expect that the OUTPUT_SCHEMA_FILE is set. If not, a warning will be issued.

To disable generation-on-start feature, you must add to your settings:

DRF_CONNECT_DOCS = {
   'OUTPUT_SCHEMA_ON_START': False,
}

GENERATION_API_KEY

In some circumstances the lack of authentication information inside the request object can cause an exception. In this case it’s possible to pass an api key through the Authorization header using the GENERATION_API_KEY.

Note

Please note that the GENERATION_API_KEY is honored only by the generation-on-start feature. If you generates your schema file using the generate_schema management command, you can specify the API key with the –apikey option.