asapi


Nameasapi JSON
Version 0.1.3 PyPI version JSON
download
home_pageNone
SummaryThin wrapper around FastAPI
upload_time2024-06-15 17:20:03
maintainerNone
docs_urlNone
authorAdrian Garcia Badaracco
requires_python<4.0,>=3.8
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # asapi

A thin opinionated wrapper around FastAPI. Because it's wrapping FastAPI you can work it into your existing projects.

## Explicit composition root

FastAPI uses callbacks inside of `Depends` to do it's dependency injection.
This forces you to end up using multiple layers of `Depends` to compose your application.
The creation of these `Depends` resources often ends up distributed across modules so it's hard to know where something is initialized.

FastAPI also has no application-level dependencies, so you end up having to use globals to share resources across requests.

`asapi` solves this by having an explicit composition root where you can define all your dependencies in one place.

Endpoints then use `Injected[DependencyType]` to get access to the dependencies they need.

## Example

```python
import anyio
from fastapi import FastAPI
from psycopg_pool import AsyncConnectionPool
from asapi import FromPath, Injected, serve, bind


app = FastAPI()


@app.get("/hello/{name}")
async def hello(
    name: FromPath[str],
    pool: Injected[AsyncConnectionPool],
) -> str:
    async with pool.connection() as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT '¡Hola ' || %(name)s || '!'", {"name": name})
            res = await cur.fetchone()
            assert res is not None
            return res[0]
```

TODO: in the future I'd like to provide a wrapper around `APIRouter` and `FastAPI` that also forces you to mark every argument to an endpoint as `Injected`, `Query`, `Path`, `Body`, which makes it explicit where arguments are coming from with minimal boilerplate.

## Run in your event loop

FastAPI recommends using Uvicorn to run your application (note: if you're using Gunicorn you probably don't need to unless you're deploying on a a 'bare meta' server with multiple cores like a large EC2 instance).

But using `uvicorn app:app` from the command line has several issues:

1. It takes control of the event loop and startup out of your hands. You have to rely on Uvicorn to configure the event loop, configure logging, etc.
2. You'll have to use ASGI lifespans to initialize your resources, or the globals trick mentioned above.
3. You can't run anything else in the event loop (e.g. a background worker).

`asapi` solves this by providing a `serve` function that you can use to run your application in your own event loop.

```python
import anyio
from asapi import serve
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root() -> dict[str, str]:
    return {"message": "Hello World"}


async def main():
    await serve(app, 8000)

if __name__ == "__main__":
    anyio.run(main)
```

Now you have full control of the event loop and can make database connections, run background tasks, etc.
Combined with the explicit composition root, you can initialize all your resources in one place:

```python
import anyio
from fastapi import FastAPI
from psycopg_pool import AsyncConnectionPool
from asapi import FromPath, Injected, serve, bind


app = FastAPI()


@app.get("/hello/{name}")
async def hello(name: FromPath[str], pool: Injected[AsyncConnectionPool]) -> str:
    async with pool.connection() as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT '¡Hola ' || %(name)s || '!'", {"name": name})
            res = await cur.fetchone()
            assert res is not None
            return res[0]


async def main() -> None:
    async with AsyncConnectionPool(
        "postgres://postgres:postgres@localhost:5432/postgres"
    ) as pool:
        bind(app, AsyncConnectionPool, pool)
        await serve(app, 8000)


if __name__ == "__main__":
    anyio.run(main)
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "asapi",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Adrian Garcia Badaracco",
    "author_email": "1755071+adriangb@users.noreply.github.com",
    "download_url": "https://files.pythonhosted.org/packages/bc/56/674e1f0ae3501fbb0faf15909127e3f326c0cdda3486a7ef67144af12757/asapi-0.1.3.tar.gz",
    "platform": null,
    "description": "# asapi\n\nA thin opinionated wrapper around FastAPI. Because it's wrapping FastAPI you can work it into your existing projects.\n\n## Explicit composition root\n\nFastAPI uses callbacks inside of `Depends` to do it's dependency injection.\nThis forces you to end up using multiple layers of `Depends` to compose your application.\nThe creation of these `Depends` resources often ends up distributed across modules so it's hard to know where something is initialized.\n\nFastAPI also has no application-level dependencies, so you end up having to use globals to share resources across requests.\n\n`asapi` solves this by having an explicit composition root where you can define all your dependencies in one place.\n\nEndpoints then use `Injected[DependencyType]` to get access to the dependencies they need.\n\n## Example\n\n```python\nimport anyio\nfrom fastapi import FastAPI\nfrom psycopg_pool import AsyncConnectionPool\nfrom asapi import FromPath, Injected, serve, bind\n\n\napp = FastAPI()\n\n\n@app.get(\"/hello/{name}\")\nasync def hello(\n    name: FromPath[str],\n    pool: Injected[AsyncConnectionPool],\n) -> str:\n    async with pool.connection() as conn:\n        async with conn.cursor() as cur:\n            await cur.execute(\"SELECT '\u00a1Hola ' || %(name)s || '!'\", {\"name\": name})\n            res = await cur.fetchone()\n            assert res is not None\n            return res[0]\n```\n\nTODO: in the future I'd like to provide a wrapper around `APIRouter` and `FastAPI` that also forces you to mark every argument to an endpoint as `Injected`, `Query`, `Path`, `Body`, which makes it explicit where arguments are coming from with minimal boilerplate.\n\n## Run in your event loop\n\nFastAPI recommends using Uvicorn to run your application (note: if you're using Gunicorn you probably don't need to unless you're deploying on a a 'bare meta' server with multiple cores like a large EC2 instance).\n\nBut using `uvicorn app:app` from the command line has several issues:\n\n1. It takes control of the event loop and startup out of your hands. You have to rely on Uvicorn to configure the event loop, configure logging, etc.\n2. You'll have to use ASGI lifespans to initialize your resources, or the globals trick mentioned above.\n3. You can't run anything else in the event loop (e.g. a background worker).\n\n`asapi` solves this by providing a `serve` function that you can use to run your application in your own event loop.\n\n```python\nimport anyio\nfrom asapi import serve\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def root() -> dict[str, str]:\n    return {\"message\": \"Hello World\"}\n\n\nasync def main():\n    await serve(app, 8000)\n\nif __name__ == \"__main__\":\n    anyio.run(main)\n```\n\nNow you have full control of the event loop and can make database connections, run background tasks, etc.\nCombined with the explicit composition root, you can initialize all your resources in one place:\n\n```python\nimport anyio\nfrom fastapi import FastAPI\nfrom psycopg_pool import AsyncConnectionPool\nfrom asapi import FromPath, Injected, serve, bind\n\n\napp = FastAPI()\n\n\n@app.get(\"/hello/{name}\")\nasync def hello(name: FromPath[str], pool: Injected[AsyncConnectionPool]) -> str:\n    async with pool.connection() as conn:\n        async with conn.cursor() as cur:\n            await cur.execute(\"SELECT '\u00a1Hola ' || %(name)s || '!'\", {\"name\": name})\n            res = await cur.fetchone()\n            assert res is not None\n            return res[0]\n\n\nasync def main() -> None:\n    async with AsyncConnectionPool(\n        \"postgres://postgres:postgres@localhost:5432/postgres\"\n    ) as pool:\n        bind(app, AsyncConnectionPool, pool)\n        await serve(app, 8000)\n\n\nif __name__ == \"__main__\":\n    anyio.run(main)\n```\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Thin wrapper around FastAPI",
    "version": "0.1.3",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "01659662528cdb612d2de77227bbad990f21861c02d13cf2f5dee5f36ce7993c",
                "md5": "bcd45cf778542253e850ff69c5799c9f",
                "sha256": "9a735d32e4ddc46326660ca5c7d741c46ebe07907b2f8851841d92b6d4f23966"
            },
            "downloads": -1,
            "filename": "asapi-0.1.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "bcd45cf778542253e850ff69c5799c9f",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 5955,
            "upload_time": "2024-06-15T17:20:01",
            "upload_time_iso_8601": "2024-06-15T17:20:01.764860Z",
            "url": "https://files.pythonhosted.org/packages/01/65/9662528cdb612d2de77227bbad990f21861c02d13cf2f5dee5f36ce7993c/asapi-0.1.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bc56674e1f0ae3501fbb0faf15909127e3f326c0cdda3486a7ef67144af12757",
                "md5": "4472adc7af5de9378a23ea3c384e75af",
                "sha256": "7ced04588fb441c87c681c0d1cfb01235b3656b7525e55479c2517ea5446b34c"
            },
            "downloads": -1,
            "filename": "asapi-0.1.3.tar.gz",
            "has_sig": false,
            "md5_digest": "4472adc7af5de9378a23ea3c384e75af",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 4834,
            "upload_time": "2024-06-15T17:20:03",
            "upload_time_iso_8601": "2024-06-15T17:20:03.720709Z",
            "url": "https://files.pythonhosted.org/packages/bc/56/674e1f0ae3501fbb0faf15909127e3f326c0cdda3486a7ef67144af12757/asapi-0.1.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-15 17:20:03",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "asapi"
}
        
Elapsed time: 0.84679s