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

By default tests are run against a database with the following connection string postgresql://postgres:postgres@localhost:5432/openapi. To use a different DB, create a .env file with a different connection string, for example:

DATASTORE=postgresql://postgres:postgres@localhost:6432/openapi

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']

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

Uploaded Source

Built Distributions

aio_openapi-2.2.0-py39-none-any.whl (54.6 kB view details)

Uploaded Python 3.9

aio_openapi-2.2.0-py38-none-any.whl (54.6 kB view details)

Uploaded Python 3.8

aio_openapi-2.2.0-py37-none-any.whl (54.7 kB view details)

Uploaded Python 3.7

File details

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

File metadata

  • Download URL: aio-openapi-2.2.0.tar.gz
  • Upload date:
  • Size: 65.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/53.0.0 requests-toolbelt/0.9.1 tqdm/4.56.2 CPython/3.9.1

File hashes

Hashes for aio-openapi-2.2.0.tar.gz
Algorithm Hash digest
SHA256 43112554ed19d51951f5a4f291154ef4c48115867a954c93954400d549d787ac
MD5 736e2b2948c1aac86cc32ee9dad8ed17
BLAKE2b-256 e288ba3d13ad0896e7161a03717455487495b15c16051ca1083bb8ad0a11ac19

See more details on using hashes here.

File details

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

File metadata

  • Download URL: aio_openapi-2.2.0-py39-none-any.whl
  • Upload date:
  • Size: 54.6 kB
  • Tags: Python 3.9
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/53.0.0 requests-toolbelt/0.9.1 tqdm/4.56.2 CPython/3.9.1

File hashes

Hashes for aio_openapi-2.2.0-py39-none-any.whl
Algorithm Hash digest
SHA256 d21b4a61c760ef4e3c8983610b98311ff793f6d44cebc8a2e5bf38f593e73eaf
MD5 1cfc27ff88880007181537d3339019c2
BLAKE2b-256 7955c3e41b2d45b19a9b1104c516d87ece5d8ad9f431e31e2d94aa5659451763

See more details on using hashes here.

File details

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

File metadata

  • Download URL: aio_openapi-2.2.0-py38-none-any.whl
  • Upload date:
  • Size: 54.6 kB
  • Tags: Python 3.8
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/53.0.0 requests-toolbelt/0.9.1 tqdm/4.56.2 CPython/3.8.7

File hashes

Hashes for aio_openapi-2.2.0-py38-none-any.whl
Algorithm Hash digest
SHA256 f79518ed921d516ce1844d979765631b8b6ab5262d66130fc76c8f2a6deb4252
MD5 17c8d25f80158103a50293c635ead8af
BLAKE2b-256 832288f414a83f60bc5a405cc48fd32f82e3f140ac45645a8e519f7f82b2b790

See more details on using hashes here.

File details

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

File metadata

  • Download URL: aio_openapi-2.2.0-py37-none-any.whl
  • Upload date:
  • Size: 54.7 kB
  • Tags: Python 3.7
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/53.0.0 requests-toolbelt/0.9.1 tqdm/4.56.2 CPython/3.7.9

File hashes

Hashes for aio_openapi-2.2.0-py37-none-any.whl
Algorithm Hash digest
SHA256 b4336f17d0260e224a224e9d2f86fe2be50fb8244bac95759eb46035e66bea74
MD5 a58b64cc4f842cec6b0de24a5a4b0b31
BLAKE2b-256 c2218ca6e653d521f7c26b1a70bd3ca282c82610c085823a99107a195a3f15af

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