swagger-py documentation

Source code is available on Github.

This project acts as a generic client library for services which follow Swagger schema.

More information on Swagger can be found on the Swagger website

It aims to be a complete replacement to swagger codegen.

Features include:

  • Synchronous and Asynchronous clients out of the box.
  • Caching of api-docs with regular staleness check.
  • Strict validations to check swagger spec is v1.2 compatible.
  • Validations on the parameter and response types.
  • Request and Response values are handled with Python types (no need to deal with JSON).
  • Doc strings are provided for Operations and Models to give more information about the API.
  • Local file path to api-docs is also acceptable.

Contents:

Quickstart

Usage

Install directly from github as:

$ pip install --upgrade git+git://github.com/Yelp/bravado@swaggerpy

Your first Hello World! (or Hello Pet)

Here is a simple one to try from REPL (like IPython):

from swaggerpy import client
swagger_client = client.get_client(
    "http://petstore.swagger.wordnik.com/api/api-docs")
client.pet.getPetById(petId=42).result()

If you were lucky, and pet Id with 42 was present, you will get back a result. It will be an instance of swaggerpy.swagger_model.Pet with attributes category, etc. You can even try result.category.id or result.tags[0].

Sample Response:

Pet(category=Category(id=0L, name=u''), status=u'', name=u'', tags=[Tag(id=0L, name=u'')], photoUrls=[u''], id=2)

If you got a 404, try some other petId.

Lets try a POST call

Here we will demonstrate how swagger-py hides all the JSON handling from the user, and makes the code more Pythonic.

Pet = swagger_client.pet.models.Pet
Category = swagger_client.pet.addPet['_models']['Category']
pet = Pet(id=42, name="tommy", category=Category(id=24))
swagger_client.pet.addPet(body=pet).result()

It should give a 200 response like: {u'code': 200, u'message': u'SUCCESS'}

Time to get Twisted! (Asynchronous client)

swagger-py gives an out of the box Asynchronous client to the user, with an optional timeout parameter.

Your first Hello World! (or Hello Pet) above can be rewritten to use Asynchronous client like so:

from swaggerpy import client
from swaggerpy.async_http_client import AsynchronousHttpClient
swagger_client = client.get_client(
    "http://petstore.swagger.wordnik.com/api/api-docs",
    AsynchronousHttpClient())
client.pet.getPetById(petId=42).result(timeout=4)

Note

timeout parameter here is the timeout (in seconds) the call will block waiting for complete response. The default time is 5 seconds.

This is too fancy for me! I want simple dict response!

swagger-py has taken care of that as well. result._flat_dict() results in complete dict response.

Hello Pet response would look like:

{'category': {'id': 0L, 'name': u''},
 'id': 2,
 'name': u'',
 'photoUrls': [u''],
 'status': u'',
 'tags': [{'id': 0L, 'name': u''}]}

Note

result.__dict__ returns only one level dict conversion, hence should be avoided.

Advanced options

Validations

swagger-py validates the schema as per v1.2 swagger spec. Validations are also done on the requests and the responses.

Validation example:

pet = Pet(id="I should be integer :(", name="tommy")
swagger_client.pet.addPet(body=pet).result()

will result in error like so:

TypeError: id's value: 'I should be integer :(' should be in types (<type 'long'>, <type 'int'>)

Note

If you think it is acceptable for fields in your response to be null, and want the validator to ignore the type check you can add allow_null=True as a parameter to result().

If response validations and type conversions are totally needed to be skipped, you can pass raw_response=True as a parameter to result() to get back raw API response.

Caching

swagger-py exposes a factory method get_client to give back the swagger client. It caches the api-docs responses so that they are not made on each API call. The default timeout is 300 seconds, which can be altered by passing``timeout`` to get_client.

Note

Caching can totally be bypassed by using swaggerpy.client.SwaggerClient() directly.

client = SwaggerClient.from_url(
    "http://petstore.swagger.wordnik.com/api/api-docs")

Adding Request Headers

swagger-py allows you to pass request headers along with any request.

Pet = swagger_client.pet.models.Pet
Category = swagger_client.pet.models.Category
pet = Pet(id=42, name="tommy", category=Category(id=24))
swagger_client.pet.addPet(
    body=pet,
    _request_options={"headers": {"foo": "bar"}},
).result()

Wrapping HTTP response error with custom class

swagger-py provided an option raise_with for wrapping HTTP errors with your custom Exception class. This is helpful for catching particular exception in your code or logging with particular exception class name.

class MyAwesomeException(Exception):
    pass
swagger_client = client.get_client(
    "http://petstore.swagger.wordnik.com/api/api-docs",
    raise_with=MyAwesomeException)

Passing Headers to the api-docs requests

swagger-py provides an option to pass custom headers with requests to api-docs

swagger_client = client.get_client(
    "http://petstore.swagger.wordnik.com/api/api-docs",
    api_doc_request_headers={'foo': 'bar'})

Docstrings

swagger-py provides docstrings to operations and models to quickly get the parameter and response types. A sample operation getPetById docstring looks like:

Docstring:
[GET] Find pet by ID
Returns a pet based on ID
Args:
        petId (int64) : ID of pet that needs to be fetched
Returns:
        Pet
Raises:
        400: Invalid ID supplied
        404: Pet not found
Class Docstring:Operation object.
Call def:   c.pet.getPetById(self, kwargs)

Even the Pet model description can be found in the docstring:

Docstring:
Attributes:
category (Category)
status (str) : pet status in the store
name (str)
tags (list(Tag))
photoUrls (list(str))
id (long) : unique identifier for the pet
Constructor information:
  Definition:Pet(self, kwargs)

Default Values

swagger-py uses the default values from the spec if the value is not provided in the request.

In the Pet Store example, operation findPetByStatus has a defaultValue of available. That means, swagger-py will plug that value if no value is provided for the parameter. Example:

swagger_client.pet.findPetByStatus()

Api-docs from file path

swagger-py also accepts api-docs from file path. Like so:

client = client.get_client('file:///path/to/api-docs')

Note

This needs a nested level file structure. Resources should be present under api-docs/. File path should not have .json with the api-docs. It will be added by swagger-py. This feature is still in beta phase.

Other alternative way is by using helper method load_file. This doesn’t need the resources to be nested.

from swaggerpy.swagger_model import load_file
client = client.get_client(load_file('/path/to/api-docs'))

Note

Both of the above methods also take an optional parameter api_base_path which can define the base path for the API call if basePath in schema is defined as ‘/’. It can be used like: client.get_client('file:///path/to/api-docs', api_base_path='http://foo')

Changelog

0.7.10 (2015-07-07)

  • Make request and response available as attrs on HTTPError

0.7.5 (2015-01-21)

  • Handle request path parameters with spaces correctly
  • Performance improvements for loading large api docs
  • Misc bug fixes

0.7.4 (2014-12-11)

  • Requests urlencode params as utf8
  • Docs related to 0.7.2
  • Declare utf-8 encoding for all files

0.7.3 (2014-12-11)

  • request logging is now done on the debug level instead of info level.

0.7.2 (2014-12-11)

  • Allow headers to be passed in the api_docs request

0.7.1 (2014-12-11)

  • Requests no longer mutate clients

0.7.0 (2014-11-26)

  • headers are no longer cached and required as part of async and http client setup.

0.6.0 (2014-10-30)

  • format=’date’ params are now represented and passed as datetime.date objects instead of datetime.datetimes.

0.5.0 (2014-08-08)

  • Allow form request parameters. (Uploading files is supported)
  • Default Values are taken if parameter not provided.
  • Detailed exception error is raised (containing server response)
  • New Optional parameters to result(): allow_null and raw_response.
  • Headers passed to HttpClient will be passed to /api-docs call as well.

0.4.0 (2014-07-15)

  • Allow MultiDict params. (for query parameters with allowMultiple: True)
  • Query Parameters with type array are not further allowed.

Configuring swagger-py

There are some configurations which can be handy.

# Default time in seconds api-docs is cached
swaggerpy.client.SWAGGER_SPEC_TIMEOUT_S = 300

# Default timeout in seconds for client to get complete response
swaggerpy.response.DEFAULT_TIMEOUT_S = 5.0

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

Indices and tables