Skip to main content

No project description provided

Project description

Falibrary

GitHub Actions GitHub PyPI - Python Version

Falcon add-on for API specification and validation.

Provide OpenAPI document and validation for flask service.

Mainly built for Machine Learning Model services.

If you're using Flask, check my another Python library Flaskerk.

Features

  • Generate API document with Redoc UI or Swagger UI :yum:
  • Less boilerplate code, annotations are really easy-to-use :sparkles:
  • Validate query, JSON data, response data with pydantic :wink:
  • Better HTTP exceptions for API services (default & customized) (JSON instead of HTML) :grimacing:

Quick Start

Install with pip install falibrary (Python 3.6+)

Basic example

import falcon
from wsgiref import simple_server
from pydantic import BaseModel

from falibrary import Falibrary

api = Falibrary(
    title='Demo Service',
    version='0.1.2',
)

class Query(BaseModel):
    text: str

class Demo():
    @api.validate(query=Query)
    def on_post(self, req, resp):
        print(req.context.query)
        pass

if __name__ == '__main__':
    app = falcon.API()
    app.add_route('/api/demo', Demo())
    api.register(app)

    httpd = simple_server.make_server('localhost', 8000, app)
    httpd.serve_forever()

Changes you need to make:

  • create model with pydantic
  • decorate the route function with Falibrary.validate()
  • specify which part you need in validate
    • query (args in url)
    • data (JSON data from request)
    • resp (response) this will be transformed to JSON data after validation
    • x (HTTP Exceptions list)
  • register to Falcon application

After that, this library will help you validate the incoming request and provide API document in /apidoc.

Parameters in Falibrary.validate Corresponding parameters in falcon
query req.context.query
data req.context.data
resp \
x \

For more details, check the document.

More features

import falcon
from wsgiref import simple_server
from pydantic import BaseModel, Schema
from random import random

from falibrary import Falibrary


api = Falibrary(
    title='Demo Service',
    version='0.1.2',
)


class Query(BaseModel):
    text: str = Schema(
        ...,
        max_length=100,
    )


class Response(BaseModel):
    label: int = Schema(
        ...,
        ge=0,
        le=9,
    )
    score: float = Schema(
        ...,
        gt=0,
        lt=1,
    )


class Data(BaseModel):
    uid: str
    limit: int
    vip: bool


class Classification():
    """
    classification demo
    """
    def on_get(self, req, resp, source, target):
        """
        get info

        test information with `source` and `target`
        """
        resp.media = {'msg': f'hello from {source} to {target}'}

    @api.validate(query=Query, data=Data, resp=Response, x=[falcon.HTTP_403])
    def on_post(self, req, resp, source, target):
        """
        post demo

        demo for `query`, `data`, `resp`, `x`
        """
        print(f'{source} => {target}')
        print(req.context.query)
        print(req.context.data)
        if random() < 0.5:
            raise falcon.HTTPForbidden("Bad luck. You're fobidden.")
        return Response(label=int(10 * random()), score=random())


if __name__ == '__main__':
    app = falcon.API()
    app.add_route('/api/{source}/{target}', Classification())
    api.register(app)

    httpd = simple_server.make_server('localhost', 8000, app)
    httpd.serve_forever()

Try it with http POST ':8000/api/zh/en?text=hello' uid=0b01001001 limit=5 vip=true.

Open the docs in http://127.0.0.1:8000/apidoc .

For more examples, check examples.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

falibrary-0.5.0.tar.gz (8.7 kB view details)

Uploaded Source

Built Distribution

falibrary-0.5.0-py3-none-any.whl (9.6 kB view details)

Uploaded Python 3

File details

Details for the file falibrary-0.5.0.tar.gz.

File metadata

  • Download URL: falibrary-0.5.0.tar.gz
  • Upload date:
  • Size: 8.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.31.1 CPython/3.7.2

File hashes

Hashes for falibrary-0.5.0.tar.gz
Algorithm Hash digest
SHA256 8b4c106809702fbd4aa5689f97e7460c34e207b6787963b0f3b10fe089d0f9dc
MD5 6d78ce8a9b84f864a6afa0dedeb8cdae
BLAKE2b-256 5dfa0a19a6e82888c7607f00e48c148d3981a75df7319b1acd82544a7f97f275

See more details on using hashes here.

File details

Details for the file falibrary-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: falibrary-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 9.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.31.1 CPython/3.7.2

File hashes

Hashes for falibrary-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f8ffa92d70bb2c10d2b889551f05f1aba775342a7b927d8ee0dcaf4394246927
MD5 58532c0aeac74d8d917b680b452052dc
BLAKE2b-256 f0a166d2d1858e70e70be1cb1ac5bb4a5a2a94867d5307725c2d2f896e5a3ca6

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page