Skip to main content

FastAPI-SQLAlchemy

FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful helpers to facilitate the completion of common tasks.

Installing

Install and update using pip:

$ pip install fastapi-sqlalchemy

Examples

Usage inside of a route

from fastapi import FastAPI
from fastapi_sqlalchemy import DBSessionMiddleware  # middleware helper
from fastapi_sqlalchemy import db  # an object to provide global access to a database session

from app.models import User

app = FastAPI()

app.add_middleware(DBSessionMiddleware, db_url="sqlite://")

# once the middleware is applied, any route can then access the database session
# from the global ``db``

@app.get("/users")
def get_users():
    users = db.session.query(User).all()

    return users

Note that the session object provided by db.session is based on the Python3.7+ ContextVar. This means that each session is linked to the individual request context in which it was created.

Usage outside of a route

Sometimes it is useful to be able to access the database outside the context of a request, such as in scheduled tasks which run in the background:

import pytz
from apscheduler.schedulers.asyncio import AsyncIOScheduler  # other schedulers are available
from fastapi import FastAPI
from fastapi_sqlalchemy import db

from app.models import User, UserCount

app = FastAPI()

app.add_middleware(DBSessionMiddleware, db_url="sqlite://")


@app.on_event('startup')
async def startup_event():
    scheduler = AsyncIOScheduler(timezone=pytz.utc)
    scheduler.start()
    scheduler.add_job(count_users_task, "cron", hour=0)  # runs every night at midnight


def count_users_task():
    """Count the number of users in the database and save it into the user_counts table."""

    # we are outside of a request context, therefore we cannot rely on ``DBSessionMiddleware``
    # to create a database session for us. Instead, we can use the same ``db`` object and
    # use it as a context manager, like so:

    with db():
        user_count = db.session.query(User).count()

        db.session.add(UserCount(user_count))
        db.session.commit()

    # no longer able to access a database session once the db() context manager has ended

    return users

Metadata

Release files for FastAPI-SQLAlchemy 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for FastAPI-SQLAlchemy 0.1.3
File Size Uploaded Provenance Actions
FastAPI-SQLAlchemy-0.1.3.tar.gz 3.9 kB Without provenance Details for FastAPI-SQLAlchemy-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for FastAPI-SQLAlchemy 0.1.3
File Interpreter ABI Platform Actions
FastAPI_SQLAlchemy-0.1.3-py3-none-any.whl Python 3 none any Details for FastAPI_SQLAlchemy-0.1.3-py3-none-any.whl

Total release size: 9.3 kB

Release files / FastAPI-SQLAlchemy-0.1.3.tar.gz

Download URL FastAPI-SQLAlchemy-0.1.3.tar.gz
Size 3.9 kB
Tags Source
SHA-256 checksum
How to use checksums
6d62f64b074a47af82981084a0b83481103c1af468c37bef04fb12c5bfa7db96
BLAKE2b-256 checksum
How to use checksums
75c96985dfe7cf2c83faf1ccd4540bb1ab36a748c6e476dd3293c7682c56529b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/46.1.1 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.7.1

Release files / FastAPI_SQLAlchemy-0.1.3-py3-none-any.whl

Download URL FastAPI_SQLAlchemy-0.1.3-py3-none-any.whl
Size 5.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1a4505b5a7b15b7aa2f4ed944fbb945fa035614666a8c321c26108e4fd9be10b
BLAKE2b-256 checksum
How to use checksums
95dd1de242184236ba44e5cfad85ac68552a18b4fa681c336d7be4ee714a1500
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/46.1.1 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.7.1

Security for FastAPI-SQLAlchemy 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page