Skip to main content

SQLAlchemy integration for API Star.

Project description

build status coverage version






José Antonio Perdiguero López

SQLAlchemy integration for API Star.


This library provides components for injecting SQLAlchemy ORM sessions into your views and event_hooks to handle commit/rollback behavior based on exceptions in your views.

Quick start

Install API Star SQLAlchemy:

pip install apistar-sqlalchemy

Add your database url to a environment variable named SQLALCHEMY_URL and create an API Star application adding components and event hooks:

from apistar_sqlalchemy.components import components
from apistar_sqlalchemy.event_hooks import event_hooks

routes = []

app = App(routes=routes, components=components, event_hooks=event_hooks)

Now you can inject SQLAlchemy Session into your views:

from sqlalchemy.orm import Session

def sqlalchemy_view(session: Session):
    # do something
    return {'message': 'something done'}

Forget about commit and rollback because there is an event hook that will handle it for you.

Full example

from apistar import App, Route, http, types, validators
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import Session

from apistar_sqlalchemy.components import components
from apistar_sqlalchemy.event_hooks import event_hooks
from apistar_sqlalchemy import database

class PuppyModel(database.Base):
    __tablename__ = "Puppy"
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String)

class PuppyType(types.Type):
    id = validators.Integer(allow_null=True, default=None)
    name = validators.String()

def list_puppies(session: Session) -> List[PuppyType]:
    return [PuppyType(puppy) for puppy in session.query(PuppyModel).all()]

def create_puppy(session: Session, puppy: PuppyType) -> http.JSONResponse:
    model = PuppyModel(**puppy)
    return http.JSONResponse(PuppyType(model), status_code=201)

routes = [
    Route('/puppy/', 'POST', create_puppy),
    Route('/puppy/', 'GET', list_puppies),

app = App(routes=routes, components=components, event_hooks=event_hooks)

Project details

Download files

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

Source Distribution

apistar-sqlalchemy-0.1.0.tar.gz (17.1 kB view hashes)

Uploaded source

Built Distribution

apistar_sqlalchemy-0.1.0-py3-none-any.whl (16.8 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page