Skip to main content

Minimal OpenAPI asynchronous server application

Project description

aio-openapi

PyPI version Python versions CircleCI codecov

This library is an asynchronous web middleware for aiohttp for serving Rest APIs with OpenAPI v 3 specification and with optional PostgreSql database.

Table of Contents

Installation

pip install aio-openapi

Development

Clone the repository and create a virtual environment venv.

Install dependencies by running the install script

./dev/install.sh

To run tests

pytest --cov

Features

  • Asynchronous web routes with aiohttp
  • Data validation, serialization and unserialization with python dataclasses
  • OpenApi v 3 auto documentation
  • SqlAlchemy expression language
  • Asynchronous DB interaction with asyncpg
  • Migrations with alembic
  • SqlAlchemy tables as python dataclasses
  • Support click command line interface
  • Optional sentry middleware

Web App

To create an openapi RESTful application follow this schema (lets call the file main.py)

from openapi.rest import rest

def create_app():
    return rest(
        openapi=dict(
            title='A REST API',
            ...
        ),
        base_path='/v1',
        allowed_tags=[...],
        validate_docs=True,
        setup_app=setup_app,
        commands=[...]
    )


def setup_app(app):
    app.router.add_routes(...)
    return app


if __name__ == '__main__':
    create_app().main()

The create_app function creates the aiohttp server application by invoking the rest function. This function adds the click command in the cli mapping entry and add documentation for routes which support OpenAPI docs. The setup_app function is used to actually setup the custom application, usually by adding middleware, routes, shutdown callbacks, database integration and so forth.

OpenAPI Documentation

The library provide tools for creating OpenAPI v 3 compliant endpoints and auto-document them.

An example from test tests/example directory

from aiohttp import web

from openapi.db.path import SqlApiPath
from openapi.spec import op


routes = web.RouteTableDef()


@routes.view('/tasks')
class TasksPath(SqlApiPath):
    """
    ---
    summary: Create and query Tasks
    tags:
        - Task
    """
    table = 'tasks'

    @op(query_schema=TaskOrderableQuery, response_schema=[Task])
    async def get(self):
        """
        ---
        summary: Retrieve Tasks
        description: Retrieve a list of Tasks
        responses:
            200:
                description: Authenticated tasks
        """
        paginated = await self.get_list()
        return paginated.json_response()

    @op(response_schema=Task, body_schema=TaskAdd)
    async def post(self):
        """
        ---
        summary: Create a Task
        description: Create a new Task
        responses:
            201:
                description: the task was successfully added
            422:
                description: Failed validation
        """
        data = await self.create_one()
        return self.json_response(data, status=201)

Database Integration

This library provides integration with [asyncpg][], an high performant asynchronous connector with PostgreSql database. To add the database extension simply use the get_db function in the applicatiuon setup_app function:

from openapi.db import get_db

def setup_app(app):
    db = get_db(app)
    meta = db.metadata

This will enable database connection and command line tools (most of them from alembic):

python main.py db --help

Websockets

This library provides a simple distributed websocket utility for creating websocket remote procedure calls (RPC) and pub/sub.

from aiohttp import web

from openapi.ws import Sockets

app = web.Application()
...
app['web_sockets'] = Sockets(app)

RPC protocol

The RPC protocol has the following structure for incoming messages

{
    "id": "abc",
    "method": "rpc_method_name",
    "payload": {
        ...
    }
}

The id is used by clients to link the request with the corresponding response. The response for an RPC call is eitrher a success

{
    "id": "abc",
    "method": "rpc_method_name",
    "result": {
        ...
    }
}

or error

{
    "id": "abc",
    "method": "rpc_method_name":
    "error": {
        ...
    }
}

Publish/Subscribe

To subscribe to messages, one need to use the Subscribe mixin with the subscribe RPC handler. Messages take the form:

{
    "channel": "channel_name",
    "event": "event_name",
    "data": {
        ...
    }
}

Environment Variables

Several environment variables are used by the library to support testing and deployment.

  • DATASTORE: PostgreSql connection string (same as SqlAlchemy syntax)
  • DBPOOL_MIN_SIZE: minimum size of database connection pool (default is 10)
  • DBPOOL_MAX_SIZE: maximum size of database connection pool (default is 10)

Project details


Release history Release notifications | RSS feed

This version

1.3.0

Download files

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

Source Distribution

aio-openapi-1.3.0.tar.gz (51.3 kB view details)

Uploaded Source

Built Distribution

aio_openapi-1.3.0-py3-none-any.whl (45.2 kB view details)

Uploaded Python 3

File details

Details for the file aio-openapi-1.3.0.tar.gz.

File metadata

  • Download URL: aio-openapi-1.3.0.tar.gz
  • Upload date:
  • Size: 51.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.30.0 CPython/3.6.8

File hashes

Hashes for aio-openapi-1.3.0.tar.gz
Algorithm Hash digest
SHA256 16e4e6674477c8896e6c9a7fc549da9076bf1bd4c5373a4b1f410a0a2ba008b2
MD5 4f8c22f4d2fa8d2000ed909b1737c7e4
BLAKE2b-256 d6b77dd19bf9d9427e9fd7e4cb2039f0483eed00f4bb2d090aaacf7513965b11

See more details on using hashes here.

File details

Details for the file aio_openapi-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: aio_openapi-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 45.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.30.0 CPython/3.6.8

File hashes

Hashes for aio_openapi-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9c46fec9686dc237075ee273a9b0e785ad562728128df8307986b5383c19337c
MD5 06a19bc37a97623dd9c98b48f4bc0727
BLAKE2b-256 2985f7fde7818b8ea911f7867980f8fe2d38f746a274e9231e1c13e913f75343

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