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
- 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
- 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 documentsession_factory (
Callable
[...
,AsyncClient
]) – used to create the session for http/s ioloader (
Optional
[Loader
]) – the backend to access referenced description documentsplugins (
Optional
[List
[Plugin
]]) – potions to cure defects in the description document or requests/responsesuse_operation_tags (
bool
) – honor tags
- Return type
- 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 documentpath (
Union
[str
,Path
,URL
]) – description document locationsession_factory (
Callable
[...
,Union
[AsyncClient
,Client
]]) – used to create the session for http/s io, defaults to use an AsyncClientloader (
Optional
[Loader
]) – the backend to access referenced description documentsplugins (
Optional
[List
[Plugin
]]) – potions to cure defects in the description document or requests/responsesuse_operation_tags (
bool
) – honor tags
- Return type
- 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 ioloader (
Optional
[Loader
]) – the backend to access referenced description documentsplugins (
Optional
[List
[Plugin
]]) – potions to cure defects in the description document or requests/responsesuse_operation_tags (
bool
) – honor tags
- Return type
- 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 documentdata (
str
) – description documentsession_factory (
Callable
[...
,Union
[AsyncClient
,Client
]]) – used to create the session for http/s io, defaults to use an AsyncClientloader (
Optional
[Loader
]) – the backend to access referenced description documentsplugins (
Optional
[List
[Plugin
]]) – potions to cure defects in the description document or requests/responsesuse_operation_tags (
bool
) – honor tags
- Return type
Requests
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.
OperationIndex
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.
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
]
-
allowEmptyValue:
- 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]
Header
- class aiopenapi3.v30.parameter.Header(**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]
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
-
required:
Optional
[bool
]
-
schema_:
Union
[Schema
,Reference
,None
]
-
style:
Optional
[str
]
-
allowEmptyValue:
- class aiopenapi3.v31.parameter.Header(**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]
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
-
required:
Optional
[bool
]
-
schema_:
Optional
[Schema
]
-
style:
Optional
[str
]
-
allowEmptyValue:
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.
Plugin Interface
Init Plugins
Init plugins are used during initialization, they can be used to modify PathItems or Schemas before generating the OperationIndex/Models.
- class Init.Context(initialized=None, schemas=None, resolved=None, paths=None)[source]
-
initialized:
Optional
[OpenAPI
] = None available in
initialized()
-
initialized:
Document Plugins
Document plugins are used to mangle description documents.
Message Plugins
Message plugins are used to mangle message.
- 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()
- headers: httpx.Headers = None
available
sending()
received()
-
marshalled:
Optional
[Dict
[str
,Any
]] = None available
marshalled()
-
operationId:
str
available
marshalled()
sending()
received()
parsed()
unmarshalled()
-
received:
Optional
[bytes
] = None available
received()
-
status_code:
Optional
[str
] = None available
received()
-
unmarshalled:
Optional
[BaseModel
] = None available
unmarshalled()
-
content_type:
Loader
The loader is used to access description documents.
aiopenapi3.loader.Loader
is the base class, providing flexibility to load description documents.
loading operation
The order of operation for the loader is:
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:
- 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.
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.
Message
HTTPError is the base class for all request/response related errors.
- exception aiopenapi3.errors.RequestError(operation, request, data, parameters)[source]
-
data:
Optional
[RequestData]
-
operation:
Optional
[OperationType]
-
parameters:
Optional
[RequestParameters]
-
request:
Optional
[RequestType]
-
data:
A RequestError typically wraps an error of the underlying httpx library.
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.
- 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
-
content_type:
- 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
-
content_length:
- exception aiopenapi3.errors.HTTPStatusError(operation, http_status, message, response)[source]
The HTTP Status is unexpected
-
http_status:
int
-
message:
str
- operation: OperationType
-
response:
Response
-
http_status:
- exception aiopenapi3.errors.ResponseDecodingError(operation, data, response)[source]
the json decoder failed
-
data:
str
- operation: OperationType
-
response:
Response
-
data:
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"]),
)
],
)