Skip to main content

Minimal OpenAPI asynchronous server application

Project description

aio-openapi

PyPI version Python versions Build Coverage Status Documentation Status Downloads

Asynchronous web middleware for aiohttp and serving Rest APIs with OpenAPI v 3 specification and with optional PostgreSql database bindings.

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

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 typing import List

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:
        - name: Task
          description: Task tag description
    """
    table = 'tasks'

    @op(query_schema=TaskOrderableQuery, response_schema=List[Task])
    async def get(self) -> web.Response:
        """
        ---
        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) -> web.Response:
        """
        ---
        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 aiohttp import web

from openapi.db import get_db

def setup_app(app: web.Application) -> None:
    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

The database container is available at the db app key:

app['db']

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",
    "response": {
        ...
    }
}

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

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-2.0.0.tar.gz (66.6 kB view details)

Uploaded Source

Built Distributions

aio_openapi-2.0.0-py39-none-any.whl (55.6 kB view details)

Uploaded Python 3.9

aio_openapi-2.0.0-py38-none-any.whl (55.6 kB view details)

Uploaded Python 3.8

aio_openapi-2.0.0-py37-none-any.whl (55.6 kB view details)

Uploaded Python 3.7

aio_openapi-2.0.0-py36-none-any.whl (55.6 kB view details)

Uploaded Python 3.6

File details

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

File metadata

  • Download URL: aio-openapi-2.0.0.tar.gz
  • Upload date:
  • Size: 66.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.9.0

File hashes

Hashes for aio-openapi-2.0.0.tar.gz
Algorithm Hash digest
SHA256 d3f1ec9870461d45e6b18eb50c4d5becb19ee2a7484157ef50de15aa3fb03b92
MD5 ac487f294fbb5d0aaece2174c458d26c
BLAKE2b-256 fc90b95c333662b0687e67042e725cf4c022b52d89fb48defd33457ecd72b217

See more details on using hashes here.

File details

Details for the file aio_openapi-2.0.0-py39-none-any.whl.

File metadata

  • Download URL: aio_openapi-2.0.0-py39-none-any.whl
  • Upload date:
  • Size: 55.6 kB
  • Tags: Python 3.9
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.9.0

File hashes

Hashes for aio_openapi-2.0.0-py39-none-any.whl
Algorithm Hash digest
SHA256 e78e871e1c6dccbe453e1f72f891f2a4e6002a60e8039cd1044f792e48bd5fdf
MD5 57632be8d680f4e8f0aecb311733f670
BLAKE2b-256 d868b04abcb5740496a052faaad510c6f9e18177d087535448d06f111367a8fd

See more details on using hashes here.

File details

Details for the file aio_openapi-2.0.0-py38-none-any.whl.

File metadata

  • Download URL: aio_openapi-2.0.0-py38-none-any.whl
  • Upload date:
  • Size: 55.6 kB
  • Tags: Python 3.8
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.8.6

File hashes

Hashes for aio_openapi-2.0.0-py38-none-any.whl
Algorithm Hash digest
SHA256 79ea02382beb9a489df66b219d28d682d66a14b2019df9e95c86b7a224371a95
MD5 a6c1f98fecf2be2b24aa1a6d58f20a48
BLAKE2b-256 7d994655e382ced837c70ca32c31e46771092b4d5b8898dfd07eae3b0852b683

See more details on using hashes here.

File details

Details for the file aio_openapi-2.0.0-py37-none-any.whl.

File metadata

  • Download URL: aio_openapi-2.0.0-py37-none-any.whl
  • Upload date:
  • Size: 55.6 kB
  • Tags: Python 3.7
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.7.9

File hashes

Hashes for aio_openapi-2.0.0-py37-none-any.whl
Algorithm Hash digest
SHA256 5ff88fdb4b94549d94a0d764d8ac2465cb48408b9f769556d77dfae20ac5175e
MD5 eb757daa2c5d961b69f528e6d23950eb
BLAKE2b-256 e77f7e4d4d0891f421004294c9e669755ad5e8c4b6cf84bd91e232993dc7c8ca

See more details on using hashes here.

File details

Details for the file aio_openapi-2.0.0-py36-none-any.whl.

File metadata

  • Download URL: aio_openapi-2.0.0-py36-none-any.whl
  • Upload date:
  • Size: 55.6 kB
  • Tags: Python 3.6
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.24.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.6.12

File hashes

Hashes for aio_openapi-2.0.0-py36-none-any.whl
Algorithm Hash digest
SHA256 a820d47d47898b0da6cf280d6b29b6c2fc803dcb9d69b399bf04a6db5bd65588
MD5 2834c045d48985976a0322994989c49d
BLAKE2b-256 efc1402a5109be675ea572d98502d436ce622346c42e25b1b6891d1c19edf004

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