API

General

class aiopenapi3.OpenAPI(url, document, session_factory=<class 'httpx.AsyncClient'>, loader=None, plugins=None, use_operation_tags=True)[source]
property _: OperationIndex

the sad smiley interface access operations by operationId

authenticate(*args, **kwargs)[source]

authenticate, multiple authentication schemes can be used simultaneously serving “or” or “and” authentication schemes

Parameters
  • args – None to remove all credentials / reset the authorizations

  • kwargs – scheme=value

static cache_load(path, plugins=None, session_factory=None)[source]

read a pickle api object from path and init the schema types

Parameters

path (Path) – cache path

Return type

OpenAPI

cache_store(path)[source]

write the pickled api object to Path to dismiss potentially local defined objects loader, plugins and the session_factory are dropped

Parameters

path (Path) – cache path

Return type

None

clone(baseurl=None)[source]

shallwo copy the api object optional set a base url

Parameters

baseurl (Optional[URL]) –

Return type

OpenAPI

createRequest(operationId)[source]

create a Request

lookup the Operation by operationId or path,method

the type of Request returned depends on the session_factory of the OpenAPI object and OpenAPI/Swagger version

Parameters

operationId (Union[str, Tuple[str, HTTPMethodType]]) – the operationId or tuple(path,method)

Return type

RequestType

Returns

the returned Request is either aiopenapi3.request.RequestBase or - in case of a httpx.AsyncClient session_factory - aiopenapi3.request.AsyncRequestBase

async classmethod load_async(url, session_factory=<class 'httpx.AsyncClient'>, loader=None, plugins=None, use_operation_tags=False)[source]

Create an asynchronous OpenAPI object from a description document.

Parameters
  • url (str) – the url of the description document

  • session_factory (Callable[..., AsyncClient]) – used to create the session for http/s io

  • loader (Optional[Loader]) – the backend to access referenced description documents

  • plugins (Optional[List[Plugin]]) – potions to cure defects in the description document or requests/responses

  • use_operation_tags (bool) – honor tags

Return type

OpenAPI

classmethod load_file(url, path, session_factory=<class 'httpx.AsyncClient'>, loader=None, plugins=None, use_operation_tags=False)[source]

Create an OpenAPI object from a description document file.

Parameters
  • url (str) – the fictive url of the description document

  • path (Union[str, Path, URL]) – description document location

  • session_factory (Callable[..., Union[AsyncClient, Client]]) – used to create the session for http/s io, defaults to use an AsyncClient

  • loader (Optional[Loader]) – the backend to access referenced description documents

  • plugins (Optional[List[Plugin]]) – potions to cure defects in the description document or requests/responses

  • use_operation_tags (bool) – honor tags

Return type

OpenAPI

classmethod load_sync(url, session_factory=<class 'httpx.Client'>, loader=None, plugins=None, use_operation_tags=False)[source]

Create a synchronous OpenAPI object from a description document.

Parameters
  • url – the url of the description document

  • session_factory (Callable[..., Client]) – used to create the session for http/s io

  • loader (Optional[Loader]) – the backend to access referenced description documents

  • plugins (Optional[List[Plugin]]) – potions to cure defects in the description document or requests/responses

  • use_operation_tags (bool) – honor tags

Return type

OpenAPI

classmethod loads(url, data, session_factory=<class 'httpx.AsyncClient'>, loader=None, plugins=None, use_operation_tags=False)[source]
Parameters
  • url (str) – the url of the description document

  • data (str) – description document

  • session_factory (Callable[..., Union[AsyncClient, Client]]) – used to create the session for http/s io, defaults to use an AsyncClient

  • loader (Optional[Loader]) – the backend to access referenced description documents

  • plugins (Optional[List[Plugin]]) – potions to cure defects in the description document or requests/responses

  • use_operation_tags (bool) – honor tags

Return type

OpenAPI

Requests

Inheritance diagram of aiopenapi3.v20.glue.Request, aiopenapi3.v30.glue.Request, aiopenapi3.v20.glue.AsyncRequest, aiopenapi3.v30.glue.AsyncRequest

Requests encapsulate the required information to call an operation. They

  • compile the actual HTTP request to be sent, including authentication information, path, headers, parameters and the body.

  • send it

  • receive the result

  • process it

  • and return the model of the data

class aiopenapi3.request.RequestBase(api, method, path, operation, servers)[source]
__call__(*args, return_headers=False, context=None, **kwargs)[source]
Parameters
  • args

  • return_headers (bool) – if set return a tuple (header, body)

  • kwargs

Return type

Union[JSON, Tuple[Dict[str, str], JSON]]

Returns

body or (header, body)

abstract property data: Optional[SchemaType]
Returns

the Schema for the body

operation: OperationType

associated OpenAPI Operation

abstract property parameters: List[ParameterType]
Returns

list of aiopenapi3.base.ParameterBase which can be used to inspect the required/optional parameters of the requested Operation

request(data=None, parameters=None, context=None)[source]

Sends an HTTP request as described by this Path

Parameters
  • data (any, should match content/type) – The request body to send.

  • parameters (dict{str: str}) – The path/header/query/cookie parameters required for the operation

  • context (Any) – The request context for use in aiopenapi3.plugin.Message

Return type

RequestBase.Response

Returns

headers, data, response

root

API document root

stream(data=None, parameters=None, context=None)[source]
Sends an HTTP request as described by this Path - but do not process the result
  • returns a tuple of Schema, httpx.Client, httpx.Response

  • requires closing the Client when done processing the response

  • requires manual processing of the data

  • intended for use with of large results

  • httpx response streaming via Response.iter_bytes()

  • combine with ijson coroutines

Parameters
  • data (any, should match content/type) – The request body to send.

  • parameters (dict{str: str}) – The path/header/query/cookie parameters required for the operation

Return type

RequestBase.StreamResponse

Returns

schema, session, response

class aiopenapi3.request.AsyncRequestBase(api, method, path, operation, servers)[source]
async __call__(*args, return_headers=False, context=None, **kwargs)[source]
Parameters
  • args

  • return_headers (bool) – if set return a tuple (header, body)

  • kwargs

Return type

Union[JSON, Tuple[Dict[str, str], JSON]]

Returns

body or (header, body)

abstract property data: Optional[SchemaType]
Returns

the Schema for the body

operation: OperationType

associated OpenAPI Operation

abstract property parameters: List[ParameterType]
Returns

list of aiopenapi3.base.ParameterBase which can be used to inspect the required/optional parameters of the requested Operation

async request(data=None, parameters=None, context=None)[source]

Sends an HTTP request as described by this Path

Parameters
  • data (any, should match content/type) – The request body to send.

  • parameters (dict{str: str}) – The path/header/query/cookie parameters required for the operation

  • context (Any) – The request context for use in aiopenapi3.plugin.Message

Return type

RequestBase.Response

Returns

headers, data, response

root

API document root

async stream(data=None, parameters=None, context=None)[source]
Sends an HTTP request as described by this Path - but do not process the result
  • returns a tuple of Schema, httpx.Client, httpx.Response

  • requires closing the Client when done processing the response

  • requires manual processing of the data

  • intended for use with of large results

  • httpx response streaming via Response.iter_bytes()

  • combine with ijson coroutines

Parameters
  • data (any, should match content/type) – The request body to send.

  • parameters (dict{str: str}) – The path/header/query/cookie parameters required for the operation

Return type

AsyncRequestBase.StreamResponse

Returns

schema, session, response

The different major versions of the OpenAPI protocol require their own Request/AsyncRequest.

class aiopenapi3.v20.glue.Request(api, method, path, operation, servers)[source]
class aiopenapi3.v20.glue.AsyncRequest(api, method, path, operation, servers)[source]
class aiopenapi3.v30.glue.Request(api, method, path, operation, servers)[source]
class aiopenapi3.v30.glue.AsyncRequest(api, method, path, operation, servers)[source]

OperationIndex

class aiopenapi3.request.OperationIndex(api, use_operation_tags)[source]
__getattr__(item)[source]

the sad smiley interface

Parameters

item (str) – the operationId

Return type

RequestType

Returns

__getitem__(item)[source]

index operator interface access operations by operationId or (path, method)

Parameters

item (Union[str, Tuple[str, HTTPMethodType]]) – operationId or tuple of path & method

Return type

RequestType

Returns

Parameters

Parameters are part of the operation specification and can be in

  • path e.g. /users/{name}

  • query e.g. /users?limit=50

  • header

  • cookie

Used to compile a aiopenapi3.request.RequestBase, not meant to be dealt with besides debugging.

Inheritance diagram of aiopenapi3.v20.parameter.Parameter, aiopenapi3.v30.parameter.Parameter, aiopenapi3.v31.parameter.Parameter, aiopenapi3.v30.parameter.Header, aiopenapi3.v31.parameter.Header

Parameter

class aiopenapi3.base.ParameterBase[source]
class aiopenapi3.v20.parameter.Parameter(**data)[source]

Describes a single operation parameter.

allowEmptyValue: Optional[bool]
collectionFormat: Optional[str]
default: Any
description: Optional[str]
enum: Optional[Any]
exclusiveMaximum: Optional[bool]
exclusiveMinimum: Optional[bool]
extensions: Optional[Any]
format: Optional[str]
in_: _In
items: Union[Items, Empty, None]
maxItems: Optional[int]
maxLength: Optional[int]
maximum: Optional[int]
minItems: Optional[int]
minLength: Optional[int]
minimum: Optional[int]
model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

multipleOf: Optional[int]
name: str
pattern: Optional[str]
required: Optional[bool]
schema_: Union[Schema, Reference, None]
type: Optional[str]
uniqueItems: Optional[bool]
class aiopenapi3.v30.parameter.Parameter(**data)[source]
allowEmptyValue: Optional[bool]
allowReserved: Optional[bool]
content: Dict[str, 'MediaType']
deprecated: Optional[bool]
description: Optional[str]
example: Optional[Any]
examples: Dict[str, Union['Example', Reference]]
explode: Optional[bool]
extensions: Optional[Any]
in_: _In
model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

name: str
required: Optional[bool]
schema_: Optional[Union[Schema, Reference]]
style: Optional[str]
class aiopenapi3.v31.parameter.Parameter(**data)[source]
allowEmptyValue: Optional[bool]
allowReserved: Optional[bool]
content: Optional[Dict[str, 'MediaType']]
deprecated: Optional[bool]
description: Optional[str]
example: Optional[Any]
examples: Dict[str, Union['Example', Reference]]
explode: Optional[bool]
extensions: Optional[Any]
in_: _In
model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

name: str
required: Optional[bool]
schema_: Optional[Schema]
style: Optional[str]

Parameter Encoding

Each of those Parameters has a different encoding strategy for different argument types. e.g. encoding a List[str] as query parameter or object in a header. Additionally Swagger 2.0 has a different encoding strategy to OpenAPI 3.x.

class aiopenapi3.v20.parameter._ParameterCodec[source]
_decode(value)[source]
_encode(name, value)[source]
class aiopenapi3.v30.parameter._ParameterCodec[source]
_decode(value)[source]
_encode(name, value)[source]

Plugin Interface

Inheritance diagram of aiopenapi3.plugin.Init, aiopenapi3.plugin.Document, aiopenapi3.plugin.Message

Init Plugins

Init plugins are used during initialization, they can be used to modify PathItems or Schemas before generating the OperationIndex/Models.

Examples

class Init.Context(initialized=None, schemas=None, resolved=None, paths=None)[source]
initialized: Optional[OpenAPI] = None

available in initialized()

paths: Optional[Dict[str, PathItemBase]] = None

available in paths()

schemas: Optional[Dict[str, SchemaBase]] = None

available in schemas()

class aiopenapi3.plugin.Init[source]
initialized(ctx)[source]

it is initialized

Return type

Context

paths(ctx)[source]

modify the paths/PathItems before initializing the Operations

Return type

Context

schemas(ctx)[source]

modify the Schema before creating Models

Return type

Context

Document Plugins

Document plugins are used to mangle description documents.

Examples

class Document.Context(url, document)[source]
document: Dict[str, Any]

available in loaded() parsed()

url: URL

available in loaded() parsed()

class aiopenapi3.plugin.Document[source]

loaded(text) -> parsed(dict)

loaded(ctx)[source]

modify the text before parsing

Return type

Context

parsed(ctx)[source]

modify the parsed dict before …

Return type

Context

Message Plugins

Message plugins are used to mangle message.

Examples

class Message.Context(request, operationId, marshalled=None, sending=None, received=None, headers=None, status_code=None, content_type=None, parsed=None, expected_type=None, unmarshalled=None)[source]
content_type: Optional[str] = None

available received()

expected_type: Optional[Type] = None

available parsed()

headers: httpx.Headers = None

available sending() received()

marshalled: Optional[Dict[str, Any]] = None

available marshalled()

operationId: str

available marshalled() sending() received() parsed() unmarshalled()

parsed: Optional[Dict[str, Any]] = None

available parsed()

received: Optional[bytes] = None

available received()

sending: Optional[str] = None

available sending()

status_code: Optional[str] = None

available received()

unmarshalled: Optional[BaseModel] = None

available unmarshalled()

class aiopenapi3.plugin.Message[source]

sending: marshalled(dict)-> sending(str)

receiving: received -> parsed -> unmarshalled

marshalled(ctx)[source]

modify the dict before sending

Return type

Context

parsed(ctx)[source]

modify the parsed dict structure

Return type

Context

received(ctx)[source]

modify the received text

Return type

Context

sending(ctx)[source]

modify the text before sending

Return type

Context

unmarshalled(ctx)[source]

modify the object

Return type

Context

Loader

The loader is used to access description documents.

aiopenapi3.loader.Loader is the base class, providing flexibility to load description documents.

Inheritance diagram of aiopenapi3.loader.FileSystemLoader, aiopenapi3.loader.WebLoader, aiopenapi3.loader.ChainLoader, aiopenapi3.loader.RedirectLoader, aiopenapi3.loader.ChainLoader

Loaders

class aiopenapi3.loader.Loader(yload=<class 'aiopenapi3.loader.YAML12Loader'>)[source]

Loaders are used to ‘get’ description documents:

  • load

  • decode

  • parse

classmethod decode(data, codec)[source]

decode bytes to ascii or utf-8

Parameters
  • data (bytes) –

  • codec (Optional[str]) –

Return type

str

Returns

get(plugins, url)[source]

load & parse the description document :type plugins: Plugins :param plugins: collection of aiopenapi3.plugin.Document plugins :type url: URL :param url: location of the description document :return:

abstract load(plugins, url, codec=None)[source]

load and decode description document

Parameters
  • plugins (Plugins) – collection of aiopenapi3.plugin.Document plugins

  • url (URL) – location of the description document

  • codec (Optional[str]) –

Returns

decoded data

parse(plugins, url, data)[source]

parse the downloaded document as json or yaml

Parameters
  • plugins (Plugins) – collection of aiopenapi3.plugin.Document plugins

  • url (URL) – location of the description document

  • data (str) – decoded data of the description document

Returns

class aiopenapi3.loader.FileSystemLoader(base, yload=<class 'aiopenapi3.loader.YAML12Loader'>)[source]

Loader to use the local filesystem

class aiopenapi3.loader.WebLoader(baseurl, session_factory=<class 'httpx.Client'>, yload=<class 'aiopenapi3.loader.YAML12Loader'>)[source]

Loader downloads data via http/s using the supplied session_factory

class aiopenapi3.loader.ChainLoader(*loaders, yload=<class 'aiopenapi3.loader.YAML12Loader'>)[source]

Loader to chain different Loaders: succeed or raise trying

The ChainLoader is useful when using multiple locations with description documents. As an example, try to lookup the referenced description documents locally or from the web.

description_documents = Path("/data/description_documents")

loader = ChainLoader(
            RedirectLoader(description_documents / "dell"),
            WebLoader(yarl.URL("https://redfish.dmtf.org/schemas/v1/")),
            WebLoader(yarl.URL("http://redfish.dmtf.org/schemas/swordfish/v1/")),
)

api = OpenAPI.load_file(
    target, yarl.URL("openapi.yaml"), loader=loader
)
class aiopenapi3.loader.RedirectLoader(base, yload=<class 'aiopenapi3.loader.YAML12Loader'>)[source]

Loader to redirect web-requests to a local directory everything but the “name” is stripped of the url

The RedirectLoader allows redirecting to local resources. A description documents URI is stripped to the file name of the document, and loaded relative to the basedir of the RedirectLoader.

RedirectLoader("description_documents/dell")

Exceptions

There is different types of Exceptions used depending on the subsystem/failure.

Inheritance diagram of aiopenapi3.errors.SpecError, aiopenapi3.errors.ReferenceResolutionError, aiopenapi3.errors.OperationParameterValidationError, aiopenapi3.errors.ParameterFormatError, aiopenapi3.errors.HTTPError, aiopenapi3.errors.RequestError, aiopenapi3.errors.ResponseError, aiopenapi3.errors.ContentTypeError, aiopenapi3.errors.HTTPStatusError, aiopenapi3.errors.ResponseDecodingError, aiopenapi3.errors.ResponseSchemaError, aiopenapi3.errors.ContentLengthExceededError, aiopenapi3.errors.HeadersMissingError

Description Document Validation

class aiopenapi3.errors.SpecError(message, element=None)[source]

This error class is used when an invalid format is found while parsing an object in the spec.

class aiopenapi3.errors.ReferenceResolutionError(message, element=None)[source]

This error class is used when resolving a reference fails, usually because of a malformed path in the reference.

class aiopenapi3.errors.ParameterFormatError(message, element=None)[source]

The specified parameter encoding is invalid for the parameter family

class aiopenapi3.errors.OperationParameterValidationError(path, method, operationid, message)[source]

The operations parameters do not match the path parameters

message: str
method: str
operationid: str
path: str

Message

exception aiopenapi3.errors.HTTPError[source]

HTTPError is the base class for all request/response related errors.

Inheritance diagram of aiopenapi3.errors.RequestError, aiopenapi3.errors.ResponseError
exception aiopenapi3.errors.RequestError(operation, request, data, parameters)[source]
data: Optional[RequestData]
operation: Optional[OperationType]
parameters: Optional[RequestParameters]
request: Optional[RequestType]

A RequestError typically wraps an error of the underlying httpx library.

exception aiopenapi3.errors.ResponseError[source]

the response can not be processed accordingly

ResponseErrors indicate the response does not match the expectation/definition in the description document. Most ResponseErrors can be mitigated around using plugins to match the protocol to the description document.

Inheritance diagram of aiopenapi3.errors.ContentTypeError, aiopenapi3.errors.ContentLengthExceededError, aiopenapi3.errors.HTTPStatusError, aiopenapi3.errors.ResponseDecodingError, aiopenapi3.errors.ResponseSchemaError, aiopenapi3.errors.HeadersMissingError
exception aiopenapi3.errors.ContentTypeError(operation, content_type, message, response)[source]

The content-type is unexpected

content_type: Optional[str]
message: str
operation: OperationType
response: Response
exception aiopenapi3.errors.ContentLengthExceededError(operation, content_length, message, response)[source]

The Content-Length exceeds our Limits

content_length: int
message: str
operation: OperationType
response: Response
exception aiopenapi3.errors.HTTPStatusError(operation, http_status, message, response)[source]

The HTTP Status is unexpected

http_status: int
message: str
operation: OperationType
response: Response
exception aiopenapi3.errors.ResponseDecodingError(operation, data, response)[source]

the json decoder failed

data: str
operation: OperationType
response: Response
exception aiopenapi3.errors.ResponseSchemaError(operation, expectation, schema, response, exception)[source]

the response data does not match the schema

exception: Optional[Exception]
expectation: ExpectedType
operation: OperationType
response: Response
schema: Optional[SchemaType]
exception aiopenapi3.errors.HeadersMissingError(operation, missing, response)[source]

the response is missing required header/s

missing: Dict[str, HeaderType]
operation: OperationType
response: Response

Extra

Cull & Reduce

Reduce & Cull are Plugins limiting the models built to the minimum required to match the requirements of the supplied Operations Code below will eleminate all schemas not required to serve the operations identified by the pattern/string match and http methods associated.

api = OpenAPI.load_sync(
    "http://127.0.0.1/api.yaml",
    plugins=[
        Cull(
            "getPetById",
            re.compile(r".*Pet.*"),
            ("/logout", ["get"]),
            (re.compile(r"^/user.*"), ["post"]),
        )
    ],
)
class aiopenapi3.extra.Reduce(*operations)[source]

The Reduce plugin removes all not listed PathItems from the paths, limits initialization to models required and removes non required schemas

__init__(*operations)[source]
Parameters

operations (List[Union[Tuple[PathMatchType, Optional[List[HTTPMethodMatchType]]], OperationIdMatchType]]) – the operation selector

class aiopenapi3.extra.Cull(*operations)[source]

The Cull plugin removes everything not required as early as possible