Resolving Swagger/OpenAPI 2.0 and 3.0.0 Parser


Keywords
swagger openapi parsing, compiler, converter, openapi, openapi2, openapi3, parser, python, python2, python3, resolver, swagger, validator
License
MITNFA
Install
pip install prance==0.10.0

Documentation

Posix Build Status Windows Build Status Docs License PyPI Python Versions Package Format Package Status

Logo

Prance provides parsers for Swagger/OpenAPI 2.0 and 3.0 API specifications in Python. It uses flex, swagger_spec_validator or openapi_spec_validator to validate specifications, but additionally resolves JSON references in accordance with the OpenAPI spec.

Mostly the latter involves handling non-URI references; OpenAPI is fine with providing relative file paths, whereas JSON references require URIs at this point in time.

Usage

Command Line Interface

After installing prance, a CLI is available for validating (and resolving external references in) specs:

# Validates with resolving
$ prance validate path/to/swagger.yml

# Validates without resolving
$ prance validate --no-resolve path/to/swagger.yml

# Fetch URL, validate and resolve.
$ prance validate http://petstore.swagger.io/v2/swagger.json
Processing "http://petstore.swagger.io/v2/swagger.json"...
 -> Resolving external references.
Validates OK as Swagger/OpenAPI 2.0!

Validation is not the only feature of prance. One of the side effects of resolving is that from a spec with references, one can create a fully resolved output spec. In the past, this was done via options to the validate command, but now there's a specific command just for this purpose:

# Compile spec
$ prance compile path/to/input.yml path/to/output.yml

Lastly, with the arrival of OpenAPI 3.0.0, it becomes useful for tooling to convert older specs to the new standard. Instead of re-inventing the wheel, prance just provides a CLI command for passing specs to the web API of swagger2openapi - a working internet connection is therefore required for this command:

# Convert spec
$ prance compile path/to/swagger.yml path/to/openapi.yml

Code

Most likely you have spec file and want to parse it:

from prance import ResolvingParser
parser = ResolvingParser('path/to/my/swagger.yaml')
parser.specification  # contains fully resolved specs as a dict

Prance also includes a non-resolving parser that does not follow JSON references, in case you prefer that.

from prance import BaseParser
parser = BaseParser('path/to/my/swagger.yaml')
parser.specification  # contains specs as a dict still containing JSON references

On Windows, the code reacts correctly if you pass posix-like paths (/c:/swagger) or if the path is relative. If you pass absolute windows path (like c:\swagger.yaml), you can use prance.util.fs.abspath to convert them.

URLs can also be parsed:

parser = ResolvingParser('http://petstore.swagger.io/v2/swagger.json')

Largely, that's it. There is a whole slew of utility code that you may or may not find useful, too. Look at the full documentation for details.

Compatibility

Different validation backends support different features.

Backend Python Version OpenAPI Version Strict Mode Notes Available From Link
swagger-spec-validator 2 and 3 2.0 only yes Slow; does not accept integer keys (see strict mode). prance 0.1 swagger_spec_validator
flex 2 and 3 2.0 only n/a Fastest; the default, and always required. prance 0.8 flex
openapi-spec-validator 3 only 2.0 and 3.0 yes Slow; does not accept integer keys (see strict mode). prance 0.11 openapi_spec_validator

You can select the backend in the constructor of the parser(s):

parser = ResolvingParser('http://petstore.swagger.io/v2/swagger.json', backend = 'openapi-spec-validator')

Only the default backend is included in the dependencies; others are detected at run-time. If you install them, they can be used:

$ pip install openapi-spec-validator
$ pip install prance
$ prance validate --backend=openapi-spec-validator path/to/spec.yml

A note on strict mode: The OpenAPI specs are a little ambiguous. On the one hand, they use JSON references and JSON schema a fair bit. But on the other hand, what they specify as examples does not always match the JSON specs.

Most notably, JSON only accepts string keys in objects. However, some keys in the specs tend to be integer values, most notably the status codes for responses. Strict mode rejects non-string keys; the default lenient mode accepts them.

Since the flex validator is not based on JSON, it does not have this issue. The strict option therefore does not apply here.

A Note on JSON References

The relevant parts of the RFC for JSON references can be condensed like this:

A JSON Reference is a JSON object, which contains a member named "$ref", which has a JSON string value. Example:

{ "$ref": "http://example.com/example.json#/foo/bar" }

(...)

Any members other than "$ref" in a JSON Reference object SHALL be ignored.

(...)

Resolution of a JSON Reference object SHOULD yield the referenced JSON value. Implementations MAY choose to replace the reference with the referenced value.

Prance is strict about ignoring additional keys, and does so by replacing the reference with the referenced value.

In practice, that means that given such a reference:

# main file
---
foo: bar
$ref: /path/to/ref

# and at /path/to/ref
---
baz: quux

Then, after resolution, the result is the following:

# resolved
---
baz: quux

That is, the key foo is ignored as the specs require. That is the reason the OpenAPI specs tend to use JSON references within schema objects, and place any other parameters as siblings of the schema object.

Extensions

Prance includes the ability to reference outside swagger definitions in outside Python packages. Such a package must already be importable (i.e. installed), and be accessible via the ResourceManager API (some more info here).

For example, you might create a package common_swag with the file base.yaml containing the definition

definitions:
  Severity:
    type: string
    enum:
    - INFO
    - WARN
    - ERROR
    - FATAL

In the setup.py for common_swag you would add lines such as

packages=find_packages('src'),
package_dir={'': 'src'},
package_data={
    '': '*.yaml'
}

Then, having installed common_swag into some application, you could now write

definitions:
  Message:
    type: object
    properties:
      severity:
        $ref: 'python://common_swag/base.yaml#/definitions/Severity'
      code:
        type: string
      summary:
        type: string
      description:
        type: string
    required:
    - severity
    - summary

Contributing

See CONTRIBUTING.md for details.

License

Licensed under MITNFA (MIT +no-false-attribs) License. See the LICENSE.txt file for details.

"Prancing unicorn" logo image Copyright (c) Jens Finkhaeuser. All rights reserved. Made by Moreven B.