Skip to content
/ doctor Public
forked from upsight/doctor

A module that assists in using JSON schemas to validate data in Flask APIs and generate API documentation

License

Notifications You must be signed in to change notification settings

dhuang/doctor

 
 

Repository files navigation

doctor

Documentation Status Build Status Pypi

This module allows you to use JSON schemas to validate data in Flask Python APIs and auto generate documentation. An example of the generated API documentation can be found in the docs. It also provides helpers for parsing and validating requests and responses in Flask apps, and supports generic schema validation for plain dictionaries.

Install

doctor can easily be installed using pip:

$ pip install doctor

Quick Start

Create a json schema with a few definitions to describe our request parameters.

---
$schema: 'http://json-schema.org/draft-04/schema#'
definitions:
  foo_id:
    description: The ID of the foo.
    type: integer
    example: 1
  fetch_bars:
    description: Fetches bars associated with a Foo.
    type: boolean
    example: true

Define the logic function that our endpoint will route to:

def get_foo(foo_id, fetch_bars=False):
    """Fetches the Foo object and optionally related bars."""
    return Foo.get_by_id(foo_id, fetch_bars=fetch_bars)

Now tie the endpoint to the logic function with a router.

from flask import Flask
from flask_restful import Api
from doctor.flask import FlaskRouter

all_routes = []
router = FlaskRouter('/path/to/schema/dir')
all_routes.extend(router.create_routes('Foo (v1)', 'foo.yaml', {
    '/foo/<int:foo_id>/': {
        'get': {
            'logic': get_foo,
        },
    },
}))

app = Flask(__name__)
api = Api(app)
for resource, route in all_routes:
    api.add_resource(resource, endpoint)

That's it, you now have a functioning API endpoint you can curl and the request is automatically validated for you based on your schema. Positional arguments in your logic function are considered required request parameters and keyword arguments are considered optional. As a bonus, using the autoflask sphinx directive, you will also get automatically generated API documentation.

Documentation

Documentation and a full example is available at readthedocs.

Running Tests

Tests can be run with tox. It will handle installing dependencies into a virtualenv, running nosetests, and rebuilding documentation.

Then run Tox:

cd doctor
tox

You can pass arguments to nosetests directly:

tox -- test/test_flask.py

About

A module that assists in using JSON schemas to validate data in Flask APIs and generate API documentation

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 100.0%