API

OpenAPI 3 Specification Object Model

openapilib.spec contains classes, each class representing an object in the OpenAPI 3 Specification

Raw example:

>>> from openapilib import serialize_spec, spec
>>> from openapilib.helpers import pretty_json
>>> api_spec = spec.OpenAPI(
...     info=spec.Info(
...         title='Foo',
...     ),
...     paths={
...         '/': spec.PathItem(
...             get=spec.Operation(
...                 responses={
...                     '200': spec.Response(
...                         description='Your favourite pet',
...                         content={
...                             'application/json': spec.MediaType(
...                                 schema=spec.Schema(
...                                     ref_name='Pet',
...                                     title='Pet',
...                                     type='object',
...                                     properties={
...                                         'name': spec.Schema.from_type(str),
...                                         'age': spec.Schema.from_type(int),
...                                     }
...                                 )
...                             )
...                         }
...                     )
...                 }
...             )
...         )
...     }
... )
>>> pretty_json(serialize_spec(api_spec))
{
  "openapi": "3.0.0",
  "info": {
    "title": "Foo",
    "version": "0.0.1-dev"
  },
  "paths": {
    "/": {
      "get": {
        "responses": {
          "200": {
            "description": "Your favourite pet",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Pet"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "Pet": {
        "title": "Pet",
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "age": {
            "type": "integer",
            "format": "int64"
          }
        }
      }
    }
  }
}
openapilib.serialize_spec(spec, disable_referencing=False)[source]

Serialize an OpenAPI spec.

Parameters:
  • spec (OpenAPI) – Spec to be serialized
  • disable_referencing – Disable automatic referencing with $ref.
Return type:

Dict[str, Any]

OpenAPI 3 Specification Types

The following two constants are useful when deciphering the spec types

openapilib.spec.REQUIRED = REQUIRED

Used as Object attribute default value to mark an object as required. When used together with the attr_required() helper, the value “None” for an attribute will be allowed, omitting the property will raise an error.

openapilib.spec.SKIP = SKIP

Used as Object attribute default value to mark an attribute as skippable, while still allowing “None” to be distinct from “unspecified”. The end result is that if the user does not specify an attribute value, the property is not included in the output. If the user specifies “None” as the attribute value, it will be included as “null”.

Types - Summary

This table is a quick-list of the implemented OpenAPI 3 Types.

OpenAPI([openapi, info, servers, paths, …]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#openapi-object
Schema([ref_name, title, description, …]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#schema-object
Info([title, description, terms_of_service, …]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#infoObject
License([name, url]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#licenseObject
Contact([name, url, email]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#contactObject
Components([schemas, responses, parameters, …]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#componentsObject
PathItem([summary, description, get, put, …]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#pathItemObject
Operation([tags, summary, description, …]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#operation-object
Parameter([ref_name, name, in_, …]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameter-object
RequestBody([ref_name, content, description]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#request-body-object
Response([ref_name, description, content]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#response-object
MediaType([schema, example]) https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#media-type-object
Reference([ref])

openapilib.spec Module

class openapilib.spec.ComponentType[source]

Bases: typing.Generic

class openapilib.spec.Components(schemas=SKIP, responses=SKIP, parameters=SKIP, examples=SKIP, request_bodies=SKIP, headers=SKIP, security_schemas=SKIP, links=SKIP, callbacks=SKIP)[source]

Bases: openapilib.base.Base

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#componentsObject

callbacks
static component_type_for_spec()[source]
create_registry_for_spec(spec)[source]
Return type:Dict[ComponentType[+T_co]]
examples
exists(spec)[source]
Return type:bool
get_ref(spec)[source]
Return type:Reference
get_ref_str(spec)[source]
Return type:str
get_registry_for_spec(spec)[source]
Return type:Optional[Dict[ComponentType[+T_co]]]
get_stored(spec)[source]
Return type:Optional[ComponentType[+T_co]]
headers
parameters
request_bodies
responses
schemas
security_schemas
store(spec)[source]
Return type:Reference
class openapilib.spec.Contact(name=SKIP, url=SKIP, email=SKIP)[source]

Bases: openapilib.base.Base

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#contactObject

email
name
url
class openapilib.spec.Info(title=REQUIRED, description=SKIP, terms_of_service=SKIP, contact=SKIP, license=SKIP, version='0.0.1-dev')[source]

Bases: openapilib.base.Base

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#infoObject

contact
description
license
terms_of_service
title
version
class openapilib.spec.License(name=SKIP, url=SKIP)[source]

Bases: openapilib.base.Base

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#licenseObject

name
url
class openapilib.spec.MediaType(schema=REQUIRED, example=SKIP)[source]

Bases: openapilib.base.Base

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#media-type-object

example
schema
class openapilib.spec.OpenAPI(openapi='3.0.0', info=REQUIRED, servers=SKIP, paths=REQUIRED, components=SKIP, security=SKIP, tags=SKIP, external_docs=SKIP)[source]

Bases: openapilib.base.Base

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#openapi-object

components
external_docs
info
openapi
paths
security
servers
tags
class openapilib.spec.Operation(tags=SKIP, summary=SKIP, description=SKIP, responses=REQUIRED, operation_id=SKIP, parameters=SKIP, request_body=SKIP)[source]

Bases: openapilib.base.Base

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#operation-object

add_tags(*tags)[source]
description
operation_id
parameters
request_body
responses
summary
tags
class openapilib.spec.Parameter(ref_name=None, name=REQUIRED, in_=<ParameterLocation.QUERY: 'query'>, description=SKIP, required=SKIP, deprecated=SKIP, allow_empty_value=SKIP, schema=SKIP)[source]

Bases: openapilib.base.Base, openapilib.base.MayBeReferenced

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameter-object

allow_empty_value
deprecated
description
in_
name
required
schema
class openapilib.spec.ParameterLocation[source]

Bases: enum.Enum

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameter-locations

COOKIE = 'cookie'
HEADER = 'header'
PATH = 'path'
QUERY = 'query'
class openapilib.spec.PathItem(summary=SKIP, description=SKIP, get=SKIP, put=SKIP, post=SKIP, delete=SKIP, options=SKIP, head=SKIP, patch=SKIP, trace=SKIP, parameters=SKIP)[source]

Bases: openapilib.base.Base

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#pathItemObject

delete
description
get
head
options
parameters
patch
post
put
summary
trace
class openapilib.spec.Reference(ref=REQUIRED)[source]

Bases: openapilib.base.Base

ref
class openapilib.spec.RequestBody(ref_name=None, content=REQUIRED, description=SKIP)[source]

Bases: openapilib.base.Base, openapilib.base.MayBeReferenced

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#request-body-object

content
description
class openapilib.spec.Response(ref_name=None, description=REQUIRED, content=SKIP)[source]

Bases: openapilib.base.Base, openapilib.base.MayBeReferenced

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#response-object

content
description
class openapilib.spec.Schema(ref_name=None, title=SKIP, description=SKIP, default=SKIP, examples=SKIP, definitions=SKIP, type=SKIP, multiple_of=SKIP, maximum=SKIP, exclusive_maximum=SKIP, minimum=SKIP, exclusive_minimum=SKIP, max_length=SKIP, min_length=SKIP, pattern=SKIP, items=SKIP, additional_items=SKIP, format=SKIP, all_of=SKIP, one_of=SKIP, not_=SKIP, any_of=SKIP, properties=SKIP, additional_properties=SKIP, required=SKIP, read_only=SKIP, write_only=SKIP, example=SKIP)[source]

Bases: openapilib.base.Base, openapilib.base.MayBeReferenced

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#schema-object

additional_items
additional_properties
all_of
any_of
default
definitions
description
example
examples
exclusive_maximum
exclusive_minimum
format
classmethod from_builtin_simple_type(fallback_handler=None, **kwargs)[source]

Create a Schema from a builtin type, such as:

Examples

>>> print(Schema.from_builtin_simple_type(int))
{
  "type": "integer",
  "format": "int64"
}
Return type:Union[Schema]
classmethod from_properties(fallback_handler=None, **kwargs)[source]

Create a Schema(type='object') from a mapping of property_name: property_type.

Example:

>>> props = {'name': str, 'age': int, 'favourite_numbers': List[int]}
>>> schema = Schema.from_properties(props, title='Pet')
>>> print(schema)
{
  "title": "Pet",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer",
      "format": "int64"
    },
    "favourite_numbers": {
      "type": "array",
      "items": {
        "type": "integer",
        "format": "int64"
      }
    }
  }
}
classmethod from_type(fallback_handler=None, **kwargs)[source]
Return type:Schema
classmethod from_type_hint(fallback_handler=None, **kwargs)[source]

Create a Schema from a typing type hint.

>>> # from typing import List
>>> schema = Schema.from_type_hint(List[int])
>>> print(schema)
{
  "type": "array",
  "items": {
    "type": "integer",
    "format": "int64"
  }
}
Return type:Union[Schema]
classmethod from_user_type(fallback_handler=None, **kwargs)[source]

Create a Schema from a user-defined class object.

Example:

>>> class Book:
>>>     name = str
>>>     pages = int
>>> print(Schema.from_user_type(Book))
{
  "properties": {
    "name": {
      "type": "string"
    },
    "pages": {
      "type": "integer",
      "format": "int64"
    }
  }
}
Return type:Schema
items
max_length
maximum
min_length
minimum
multiple_of
not_
one_of
pattern
properties
read_only
required
title
write_only
exception openapilib.spec.SchemaHelperError[source]

Bases: Exception

exception openapilib.spec.SchemaHelperUnhandled[source]

Bases: Exception

Raised by Schema.from_type methods if they do not handle the provided source.

class openapilib.spec.StringFormat[source]

Bases: enum.Enum

http://json-schema.org/latest/json-schema-validation.html#rfc.section.8.3

DATETIME = 'date-time'
EMAIL = 'email'
HOSTNAME = 'hostname'
IPV4 = 'ipv4'
IPV6 = 'ipv6'
JSON_POINTER = 'json-pointer'
URI = 'uri'
URI_REFERENCE = 'uri-reference'
URI_TEMPLATE = 'uri-template'
openapilib.spec.T_Component

alias of ComponentType

openapilib.spec.attr_registry(**kwargs)[source]
openapilib.spec.attr_required(**kwargs)[source]
openapilib.spec.attr_skippable(**kwargs)[source]
Return type:Union[Sentinel, ~T]
openapilib.spec.enum_to_string(member)[source]
openapilib.spec.validate_required(instance, attribute, value)[source]

Helpers

class openapilib.serialization.SerializationContext(disable_referencing=False, components=None)[source]
components
disable_referencing
serialize(obj)[source]
serialize_maybe_reference(spec)[source]

Serialize an object that may be referenced by storing the definition in Components and returning a reference.

serialize_value(value)[source]

Serializes container types, such as list, dict, tuple, set.

openapilib.serialization.filter_attributes(attribute, value)[source]
openapilib.serialization.rename_key(key, a)[source]
Return type:str
openapilib.serialization.serialize(spec)[source]

Recursively convert a spec to a dictionary.

This method can be used for testing and development, or as a utility.

If you want to serialize an OpenAPI object, use serialize_spec.

References are not generated by this method.

Return type:Dict[str, Any]
openapilib.serialization.serialize_spec(spec, disable_referencing=False)[source]

Serialize an OpenAPI spec.

Parameters:
  • spec (OpenAPI) – Spec to be serialized
  • disable_referencing – Disable automatic referencing with $ref.
Return type:

Dict[str, Any]

openapilib.serialization.spec_to_dict(spec)[source]

Serializes instances of objects that inherit from Base.

class openapilib.sentinel.Sentinel(name, doc=None)[source]

A class to be used as a canary value instead of the commonly used. Use this where you would sometimes otherwise use NAME = object(), as in

>>> DEFAULT = object()
>>> data = {'foo': None}
>>> def get(key, default=DEFAULT):
...     try:
...         data[key]
...     except KeyError as exc:
...         if default is not DEFAULT:
...             return default
...         else:
...             raise exc

This class has the advantage of the “name” property, which will get printed when calling repr(sentinel_instance).

>>> DEFAULT = Sentinel('DEFAULT')
>>> repr(DEFAULT)
'DEFAULT'