jsonapi.sqlalchemy

Contains the sqlalchemy database adapter and JSONapi schema.

Tutorial

If you have an sqlalchemy model, use the sqlalchemy database adapter and the sqlalchemy JSONapi schema:

schema = jsonapi.sqlalchemy.Serializer(MyModel)
db = jsonapi.sqlalchemy.Database(sessionmaker=Session)

However, here is a short example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python3

import jsonapi
import jsonapi.sqlalchemy

import sqlalchemy
import sqlalchemy.orm
import sqlalchemy.ext.declarative


# Create the sqlalchemy base, engine and the sessionmaker.
Base = sqlalchemy.ext.declarative.declarative_base()
engine = sqlalchemy.create_engine("sqlite:///example.db")

Session = sqlalchemy.orm.sessionmaker()
Session.configure(bind=engine)


class User(Base):

    __tablename__ = "users"

    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    name = sqlalchemy.Column("name", sqlalchemy.String(50))


class Post(Base):

    __tablename__ = "posts"

    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    text = sqlalchemy.Column(sqlalchemy.Text)

    author_id = sqlalchemy.Column(
        sqlalchemy.Integer, sqlalchemy.ForeignKey("users.id")
    )
    author = sqlalchemy.orm.relationship(
        "User", backref=sqlalchemy.orm.backref("posts")
    )


# Create the API and add the models.
db = jsonapi.sqlalchemy.Database(sessionmaker=Session)
api = jsonapi.base.api.API("/api", db)

user_schema = jsonapi.sqlalchemy.Schema(User)
post_schema = jsonapi.sqlalchemy.Schema(Post)

api.add_type(user_schema)
api.add_type(post_schema)

sessionmaker

Performing queries with sqlalchemy requires a Session. The database adapter requires a function sessionmaker, which returns a valid session.

You can provide the sessionmaker as init argument for the database adapter:

db = jsonapi.sqlalchemy.Database(sessionmaker=get_session)

or you use the settings dictionary of the API:

api.settings["sqlalchemy_sessionmaker"] = get_session

API

class jsonapi.sqlalchemy.schema.Schema(resource_class)[source]

Bases: jsonapi.base.schema.Schema

This schema subclass finds also sqlalchemy attributes and relationships defined on the resource class.

Parameters:
  • resource_class – The sqlalchemy model
  • typename (str) – The typename of the resources in the JSONapi. If not given, it is derived from the resource class.
find_sqlalchemy_markers()[source]
class jsonapi.sqlalchemy.database.Database(sessionmaker=None, api=None)[source]

Bases: jsonapi.base.database.Database

This adapter must be chosen for sqlalchemy models.

Parameters:
  • sessionmaker – The function used to get a sqlalchemy session. If not given, the api settings must contain a sqlalchemy_sessionmaker key.
  • api (jsonapi.base.api.API) –
init_api(api)[source]
session()[source]

Todo

Todo

Find hybrid methods and properties