swaggerpy Package

swaggerpy Package

http_client Module

HTTP client abstractions.

class swaggerpy.http_client.ApiKeyAuthenticator(host, api_key, param_name=u'api_key')

Bases: swaggerpy.http_client.Authenticator

?api_key authenticator.

This authenticator adds a query parameter to specify an API key.

Parameters:
  • host – Host to authenticate for.
  • api_key – API key.
  • param_name – Query parameter specifying the API key.
apply(request)

Apply authentication to a request.

Parameters:request – Request to add authentication information to.
class swaggerpy.http_client.Authenticator(host)

Bases: object

Authenticates requests.

Parameters:host – Host to authenticate for.
apply(request)

Apply authentication to a request.

Parameters:request – Request to add authentication information to.
matches(url)

Returns true if this authenticator applies to the given url.

Parameters:url – URL to check.
Returns:True if matches host, port and scheme, False otherwise.
class swaggerpy.http_client.BasicAuthenticator(host, username, password)

Bases: swaggerpy.http_client.Authenticator

HTTP Basic authenticator.

Parameters:
  • host – Host to authenticate for.
  • username – Username.
  • password – Password
apply(request)

Apply authentication to a request.

Parameters:request – Request to add authentication information to.
class swaggerpy.http_client.HttpClient

Bases: object

Interface for a minimal HTTP client.

request(method, url, params=None, data=None)

Issue an HTTP request.

Parameters:
  • method (str) – HTTP method (GET, POST, DELETE, etc.)
  • url (str) – URL to request
  • params (dict) – Query parameters (?key=value)
  • data (Dictionary, bytes, or file-like object) – Request body
Returns:

Implementation specific response object

set_api_key(host, api_key, param_name=u'api_key')

Configures client to use api_key authentication.

The api_key is added to every query parameter sent.

Parameters:
  • host – Hostname to limit authentication to.
  • api_key – Value for api_key.
  • param_name – Parameter name to use in query string.
set_basic_auth(host, username, password)

Configures client to use HTTP Basic authentication.

Parameters:
  • host – Hostname to limit authentication to.
  • username – Username
  • password – Password
start_request(request_params)
Parameters:request_params (dict) – Complete request data.
Returns:The client’s request object
class swaggerpy.http_client.SynchronousEventual(session, request)

Bases: object

An adapter which supports the crochet.EventualResult interface for the SynchronousHttpClient class.

cancel()
wait(timeout=None)

Perform the request.

Parameters:timeout – timeout for the request, in seconds
class swaggerpy.http_client.SynchronousHttpClient

Bases: swaggerpy.http_client.HttpClient

Synchronous HTTP client implementation.

apply_authentication(request)
authenticated_request(request_params)
set_api_key(host, api_key, param_name=u'api_key')

Configures client to use api_key authentication.

The api_key is added to every query parameter sent.

Parameters:
  • host – Hostname to limit authentication to.
  • api_key – Value for api_key.
  • param_name – Parameter name to use in query string.
set_basic_auth(host, username, password)

Configures client to use HTTP Basic authentication.

Parameters:
  • host – Hostname to limit authentication to.
  • username – Username
  • password – Password
start_request(request_params)
Returns:request
Return type:requests.Request

async_http_client Module

Asynchronous HTTP client abstractions.

class swaggerpy.async_http_client.AsyncResponse(req, resp, data)

Bases: object

Remove the property text and content and make them as overridable attrs

json(**kwargs)
raise_for_status()

Raises stored HTTPError, if one occured.

class swaggerpy.async_http_client.AsynchronousHttpClient

Bases: swaggerpy.http_client.HttpClient

Asynchronous HTTP client implementation.

fetch_deferred(request_params)

The main core to start the reacter and run the API in the background. Also the callbacks are registered here

Returns:crochet EventualResult
start_request(request_params)

Sets up the request params as per Twisted Agent needs. Sets up crochet and triggers the API request in background

Parameters:request_params (dict) – request parameters for API call
Returns:crochet EventualResult
swaggerpy.async_http_client.listify_headers(headers)

Twisted agent requires header values as lists

swagger_type Module

Code to check the validity of swagger types and conversion to python types

class swaggerpy.swagger_type.SwaggerTypeCheck(name, value, type_, models=None, allow_null=False, to_wire=False)

Bases: object

Initialization of the class checks for the validity of the value to the type.

Raises TypeError/AssertionError if validation fails

swaggerpy.swagger_type.extract_format(_type_format)

returns the Format extracted from Type:Format Type:Format is the convention followed for type conversion to string

Parameters:_type_format (str or unicode) – converted internal type format eg. “integer:int64”
Returns:extracted format eg. “int64”
swaggerpy.swagger_type.get_array_item_type(type_)

returns the Array Type extracted from ‘Array:ArrayType’ ‘Array:ArrayType’ is the convention followed for converting swagger array type into a string

Parameters:type (str or unicode) – converted internal type format eg. “array:integer:int64”
Returns:extracted array type eg. “integer:int64”
swaggerpy.swagger_type.get_primitive_mapping(type_)

Returns the Python type from the swagger internal type string

Parameters:type (str or unicode) – swagger type, eg. integer, number:float
Return type:type eg. int, string
swaggerpy.swagger_type.get_swagger_type(json_)

Converts swagger type from json to swagger internal type

Example:

{
    ...
    "type": "array",
    "items": {
         "type": "integer",
         "format": "int64"
         }
    ...
}

Returns:

"array:integer:int64"
Parameters:json (dict) – dict containing type and rest of the data
Return type:str or unicode
swaggerpy.swagger_type.get_swagger_types(props)

Converts dict of swagger types to dict of swagger internal types

Parameters:props (dict) – dict of json properties
Return type:dict
swaggerpy.swagger_type.is_array(type_)

checks whether the swagger type is array :rtype: boolean

swaggerpy.swagger_type.is_complex(type_)

checks whether the swagger type is neither primitive nor array :rtype: boolean

swaggerpy.swagger_type.is_file(type_)

checks whether the swagger type is file :rtype: boolean

swaggerpy.swagger_type.is_primitive(type_)

checks whether the swagger type is primitive :rtype: boolean

swaggerpy.swagger_type.primitive_formats()

returns Swagger primitive formats allowed after internal conversion.

Returns:a list of typed formats eg. [‘integer:int64’, ‘string:str’]
Return type:list
swaggerpy.swagger_type.primitive_types()

returns all allowed Swagger primitive types

Returns:a list of only types
Return type:list
swaggerpy.swagger_type.swagger_to_py_type(type_)

returns the python type from swagger type

Parameters:type (str or unicode) – swagger internal type
Return type:Python type
swaggerpy.swagger_type.swagger_to_py_type_string(type_)

returns the string repr of Python type. Used during docstring display of a Model

Parameters:type (str or unicode) – swagger internal type
Return type:str or unicode

response Module

Code for checking the response from API. If correct, it proceeds to convert it into Python class types

class swaggerpy.response.HTTPFuture(http_client, request_params, post_receive)

Bases: object

A future which inputs HTTP params

cancel()

Try to cancel the API (meaningful for Asynchronous client)

cancelled()

Checks if API is cancelled Once cancelled, it can’t be resumed

result(**kwargs)

Blocking call to wait for API response If API was cancelled earlier, CancelledError is raised If everything goes fine, callback registered is triggered with response

Parameters:
  • timeout (integer) – timeout in seconds to wait for response
  • allow_null (boolean) – if True, allow null fields in response
  • raw_response (boolean) – if True, return raw response w/o any validations
class swaggerpy.response.SwaggerResponseConstruct(response, type_, models)

Bases: object

create_object()

Only public method in the class

Creates the object assuming the response is checked and valid

Returns:instance of complex Py object or simple primitive object
swaggerpy.response.handle_response_errors(e)
Parameters:e – Exception object
Raises:HTTPError
class:swaggerpy.exception.HTTPError
swaggerpy.response.post_receive(response, type_, models, **kwargs)

Convert the response body to swagger models.

Example API Response

{
    "id": 1,
    "category": {
        "name": "chihuahua"
    },
    "name": "tommy",
    "photoUrls": [
        ""
    ],
    "tags": [
        {
            "name": "cute"
        }
    ],
    "status": "available"
}

SwaggerResponse:

..code-block:: python

Pet(category=Category(id=0L, name=u’chihuahua’),
status=u’available’, name=u’tommy’, tags=[Tag(id=0L, name=u’cute’)], photoUrls=[u’‘], id=1)
Parameters:
  • response (dict) – response body
  • type (str or unicode) – expected swagger type
  • models (namedtuple) – namedtuple which maps complex type string to py type

exception Module

exception swaggerpy.exception.CancelledError

Bases: exceptions.Exception

Error raised when result() is called from HTTPFuture and call was actually cancelled

exception swaggerpy.exception.HTTPError(*args, **kwargs)

Bases: exceptions.IOError

Initialize HTTPError with ‘response’ and ‘request’ object

exception swaggerpy.exception.SwaggerError(msg, context, cause=None)

Bases: exceptions.Exception

Raised when an error is encountered mapping a response objects into a model.

Parameters:
  • msg – String message for the error.
  • context – ParsingContext object
  • cause – Optional exception that caused this one.

processors Module

Swagger processors enrich and validate the Swagger data model.

This can be to make templating easier, or ensure values required for a particular use case (such as ensuring that description and summary fields exist)

class swaggerpy.processors.ParsingContext

Bases: object

Context information for parsing.

This object is immutable. To change contexts (like adding an item to the stack), use the next() and next_stack() functions to build a new one.

is_empty()

Tests whether context is empty.

Returns:True if empty, False otherwise.
pop()

Pops the most recent object out of the context

push(obj_type, json, id_field)

Pushes a new self-identifying object into the context.

Parameters:
  • json (dict) – Specifies type of object json represents
  • json – Current Jsonified object.
  • id_field (str) – Field name in json that identifies it.
push_str(obj_type, json, id_string)

Pushes a new object into the context.

Parameters:
  • obj_type (str) – Specifies type of object json represents
  • json (dict) – Current Jsonified object.
  • id_string (str) – Identifier of the given json.
class swaggerpy.processors.SwaggerProcessor

Bases: object

Post processing interface for Swagger API’s.

This processor can add fields to model objects for additional information to use in the templates.

apply(resources)

Apply this processor to a loaded Swagger definition.

It assumes Swagger resource listing is valid and verified.

Parameters:resources (dict) – Top level Swagger definition.
pre_apply(resources)

Apply this processor to a Swagger definition before loading resources.

It fails if resource listing is not valid.

Parameters:resources (dict) – Top level Swagger definition.
process_api_declaration(resources, resource, context)

Post process a resource object.

This is parsed from a .json file reference by a resource listing’s ‘api’ array.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • context (ParsingContext) – Current context in the API.
process_model(resources, resource, model, context)

Post process a model from a resources model dictionary.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • model – Model object.
  • context (ParsingContext) – Current context in the API.
process_operation(resources, resource, api, operation, context, model_ids)

Post process an operation on an api.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • api – API object
  • operation – Operation object.
  • context (ParsingContext) – Current context in the API.
process_parameter(resources, resource, api, operation, parameter, context, model_ids)

Post process a parameter on an operation.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • api – API object
  • operation – Operation object.
  • parameter – Parameter object.
  • context (ParsingContext) – Current context in the API.
process_property(resources, resource, model, prop, context, model_ids)

Post process a property from a model.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • model – Model object.
  • prop – Property object.
  • context (ParsingContext) – Current context in the API.
process_resource_api(resources, resource, api, context)

Post process entries in a resource’s api array

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • api – API object
  • context (ParsingContext) – Current context in the API.
process_resource_listing(resources, context)

Post process a resources.json object.

Parameters:
  • resources – ResourceApi object.
  • context (ParsingContext) – Current context in the API.
process_resource_listing_api(resources, listing_api, context)

Post process entries in a resource.json’s api array.

Parameters:
  • resources – Resource listing object
  • listing_api – ResourceApi object.
  • context (ParsingContext) – Current context in the API.
process_response_message(resources, resource, api, operation, response_message, context, model_ids)

Post process an Response on an operation.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • api – API object
  • operation – Operation object.
  • response – Response object.
  • context (ParsingContext) – Current context in the API.

swagger_model Module

class swaggerpy.swagger_model.FileEventual(path)

Bases: object

Adaptor which supports the crochet.EventualResult interface for retrieving api docs from a local file.

class FileResponse(data)

Bases: object

json()
cancel()
get_path()
wait(timeout=None)
class swaggerpy.swagger_model.ValidationProcessor

Bases: swaggerpy.processors.SwaggerProcessor

A processor that validates the Swagger model.

process_api_declaration(resources, resource, context)

Post process a resource object.

This is parsed from a .json file reference by a resource listing’s ‘api’ array.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • context (ParsingContext) – Current context in the API.
process_model(resources, resource, model, context)

Post process a model from a resources model dictionary.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • model – Model object.
  • context (ParsingContext) – Current context in the API.
process_operation(resources, resource, api, operation, context, model_ids)

Post process an operation on an api.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • api – API object
  • operation – Operation object.
  • context (ParsingContext) – Current context in the API.
process_parameter(resources, resource, api, operation, parameter, context, model_ids)

Post process a parameter on an operation.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • api – API object
  • operation – Operation object.
  • parameter – Parameter object.
  • context (ParsingContext) – Current context in the API.
process_property(resources, resource, model, prop, context, model_ids)

Post process a property from a model.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • model – Model object.
  • prop – Property object.
  • context (ParsingContext) – Current context in the API.
process_resource_api(resources, resource, api, context)

Post process entries in a resource’s api array

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • api – API object
  • context (ParsingContext) – Current context in the API.
process_resource_listing(resources, context)

Post process a resources.json object.

Parameters:
  • resources – ResourceApi object.
  • context (ParsingContext) – Current context in the API.
process_resource_listing_api(resources, listing_api, context)

Post process entries in a resource.json’s api array.

Parameters:
  • resources – Resource listing object
  • listing_api – ResourceApi object.
  • context (ParsingContext) – Current context in the API.
process_response_message(resources, resource, api, operation, response_message, context, model_ids)

Post process an Response on an operation.

Parameters:
  • resources – Resource listing object
  • resource – resource object.
  • api – API object
  • operation – Operation object.
  • response – Response object.
  • context (ParsingContext) – Current context in the API.
swaggerpy.swagger_model.compare(first, second)

Compares the two types for equivalence.

If a type composes another model types, .__dict__ recurse on those and compares again on those dict values

swaggerpy.swagger_model.create_flat_dict(model)

Generates __dict__ of the model traversing recursively each of the list item of an array and calling it again. While __dict__ only converts it on one level.

param model:generated model type reference
type model:type
returns:flat dict repr of the model

Example:

Pet(id=3, name="Name", photoUrls=["7"], tags=[Tag(id=2, name='T')])

converts to:

{'id': 3,
 'name': 'Name',
 'photoUrls': ['7'],
 'tags': [{'id': 2,
           'name': 'T'}
         ]
 }
swaggerpy.swagger_model.create_model_docstring(props)

Generates a docstring for the type from the props

param props:dict containing properties of the type
type props:dict
returns:Generated string

Example:

"Pet": {
    "id": "Pet",
    "properties": {
        "id": {
            "type": "integer",
            "format": "int64",
            "description": "unique identifier for the pet",
        },
        "category": {
            "$ref": "Category"
        },
        "name": {
            "type": "string"
        },
        "status": {
            "type": "string",
            "description": "pet status in the store",
        }
    }
}

Result:

Attributes:

    category (Category)
    status (str) : pet status in the store
    name (str)
    id (long) : unique identifier for the pet
swaggerpy.swagger_model.create_model_repr(model)

Generates the repr string for the model

Parameters:model (type) – generated model type reference
Returns:repr string for the model
swaggerpy.swagger_model.create_model_type(model)

Create a dynamic class from the model data defined in the swagger spec.

The docstring for this class is dynamically generated because generating the docstring is relatively expensive, and would only be used in rare cases for interactive debugging in a REPL.

Parameters:model – Resource model dict with keys id and properties
Returns:dynamic type created with attributes, docstrings attached
Return type:type
class swaggerpy.swagger_model.docstring_property(func)

Bases: object

swaggerpy.swagger_model.is_file_scheme_uri(url)
swaggerpy.swagger_model.load_file(resource_listing_file, http_client=None)

Loads a resource listing file.

Parameters:
  • http_client – HTTP client interface.
  • resource_listing_file – File name for a resource listing.
Returns:

Processed object model from

Raise:

IOError: On error reading api-docs.

swaggerpy.swagger_model.load_resource_listing(url, http_client, base_url=None, request_options=None)

Load a complete swagger api spec and return all schemas compiled into a single dict.

Parameters:
  • url – url to the swagger spec (file or http)
  • http_client – a swaggerpy.http_client.HttpClient for performing the requests to fetch api documents.
  • base_url – optional url to use as the base url for api doc paths
  • request_options – mapping of additional fields to specify in the http request to fetch resources.
swaggerpy.swagger_model.load_url(url, http_client=None, **kwargs)

Loads a resource listing.

Parameters:
  • resource_listing_url – URL for a resource listing.
  • http_client – HTTP client interface.
  • base_url – Optional URL to be the base URL for finding API declarations. If not specified, ‘basePath’ from the resource listing is used.
Returns:

Processed object model from

Raise:

IOError, URLError: On error reading api-docs.

swaggerpy.swagger_model.set_props(model, **kwargs)

Constructor for the generated type - assigns given or default values

Parameters:
  • model (type) – generated model type reference
  • kwargs (dict) – attributes to override default values of constructor
swaggerpy.swagger_model.start_request(http_client, url, request_options)

Download and parse JSON from a URL.

Parameters:
Returns:

an object with a :func`wait` method which returns the api docs

swaggerpy.swagger_model.validate_params_body_or_form(json)

Validates that form request parameters are present or body request params but not both

swaggerpy.swagger_model.validate_required_fields(json, required_fields, context)

Checks a JSON object for a set of required fields.

If any required field is missing, a SwaggerError is raised.

Parameters:
  • json – JSON object to check.
  • required_fields – List of required fields.
  • context – Current context in the API.
swaggerpy.swagger_model.validate_type_or_ref(json, model_ids, allowed_types, allowed_refs, context)

Validates that either type OR ref is present in the json

Parameters:
  • json – dict to check whether type or ref is present
  • model_ids – list of allowed $ref ids (all models)
  • allowed_types – list of all kind of types allowed
  • allowed_refs – list of all kind of refs allowed
  • context – only used for Request Operation and Paramter

client Module

The SwaggerClient provides an interface for making API calls based on a swagger spec, and returns responses of python objects which build from the API response.

Structure Diagram:

+---------------------+           +---------------------+
|                     |           |                     |
|    SwaggerClient    <-----------+  SwaggerClientCache |
|                     |   caches  |                     |
+------+--------------+           +---------------------+
       |
       |  has many
       |
+------v--------------+
|                     |
|     Resource        +------------------+
|                     |                  |
+------+--------------+         has many |
       |                                 |
       |  has many                       |
       |                                 |
+------v--------------+           +------v--------------+
|                     |           |                     |
|     Operation       |           |    SwaggerModel     |
|                     |           |                     |
+------+--------------+           +---------------------+
       |
       |  uses
       |
+------v--------------+
|                     |
|     HttpClient      |
|                     |
+---------------------+

To get a client with caching

client = swaggerpy.client.get_client(api_docs_url)

without caching

client = swaggerpy.client.SwaggerClient.from_url(api_docs_url)
class swaggerpy.client.CacheEntry(item, ttl, timestamp=None)

Bases: object

An entry in the cache. Each item has it’s own ttl.

Parameters:
  • item – the item to cache
  • ttl (int) – time-to-live in seconds after which the client expires
is_stale(timestamp=None)

Checks if the instance has become stale :return: True if the cache item is stale, False otherwise

class swaggerpy.client.Operation(uri, operation, http_client, models)

Bases: object

Perform a request by taking the kwargs passed to the call and constructing an HTTP request.

class swaggerpy.client.Resource(name, operations)

Bases: object

Swagger resource, described in an API declaration.

classmethod from_api_doc(api_doc, http_client, base_path, url_base=None)
Parameters:
  • api_doc (dict) – api doc which defines this resource
  • http_client – a swaggerpy.http_client.HttpClient
  • base_path – base url to perform api requests. Used to override the path provided in the api spec
  • url_base – a url used as the base for resource definitions that include a relative basePath
class swaggerpy.client.SwaggerClient(api_url, resources)

Bases: object

A client for accessing a Swagger-documented RESTful service.

Parameters:
  • api_url – the url for the swagger api docs, only used for the repr.
  • resources – a list of :Resource: objects used to perform requests
classmethod from_resource_listing(resource_listing, http_client=None, api_base_path=None, url=None)

Build a SwaggerClient from swagger api docs

Parameters:
  • resource_listing – a dict with a list of api definitions
  • http_client (swaggerpy.http_client.HttpClient) – an HTTP client used to perform requests
  • api_base_path (str) – a url, override the path used to make api requests
  • url (str) – the url used to retrieve the resource listing
classmethod from_url(url, http_client=None, api_base_path=None, request_options=None)

Build a SwaggerClient from a url to api docs describing the api.

Parameters:
  • url (str) – url pointing at the swagger api docs
  • http_client (swaggerpy.http_client.HttpClient) – an HTTP client used to perform requests
  • api_base_path (str) – a url, override the path used to make api requests
  • request_options (dict) – extra values to pass with api docs requests
class swaggerpy.client.SwaggerClientCache

Bases: object

Cache to store swagger clients and refetch the api-docs if the client becomes stale

build_client(api_docs, *args, **kwargs)
swaggerpy.client.add_param_to_req(param, value, request)

Populates request object with the request parameters

Parameters:
  • param (dict) – swagger spec details of a param
  • value – value for the param given in the API call
  • request – request object to be populated
swaggerpy.client.append_name_to_api(api_entry)
swaggerpy.client.build_models(model_dicts)
swaggerpy.client.build_resources_from_spec(http_client, apis, api_base_path, url_base)
swaggerpy.client.create_operation_docstring(json_)

Builds Operation docstring from the json dict

Parameters:json (dict) – data to create docstring from
Returns:string giving meta info

Example:

client.pet.findPetsByStatus?

Outputs:

[GET] Finds Pets by status

Multiple status values can be provided with comma seperated strings
Args:
        status (string) : Statuses to be considered for filter
        from_date (string) : Start date filter
Returns:
        array
Raises:
        400: Invalid status value
swaggerpy.client.get_client(*args, **kwargs)

Factory method to generate SwaggerClient instance.

Note

This factory method uses a global which maintains the state of swagger client. Use SwaggerClientCache if you want more control.

To change the freshness timeout, simply pass an argument: ttl=<seconds>

To remove the caching functionality, pass: ttl=0

Note

It is OKAY to call get_swagger_client(…) again and again. Do not keep a reference to the generated client and make it long lived as it strips out the refetching functionality.

Parameters:
  • api_docs_url (str) – url for swagger api docs used to build the client
  • ttl – (optional) Timeout in secs. after which api-docs is stale
Returns:

SwaggerClient

swaggerpy.client.get_resource_url(base_path, url_base, resource_base_path)
swaggerpy.client.handle_form_param(name, value, type_, request)
swaggerpy.client.stringify_body(value)

Json dump the value to string if not already in string

swaggerpy.client.validate_and_add_params_to_request(param, value, request, models)

Validates if a required param is given And wraps ‘add_param_to_req’ to populate a valid request

Parameters:
  • param (dict) – swagger spec details of a param
  • value – value for the param given in the API call
  • request – request object to be populated
  • models (namedtuple) – models tuple containing all complex model types