Skip to content

API Creation

Thomas Pollet edited this page Apr 25, 2020 · 5 revisions

Exposing Instances

SAFRS' main purpose is to easily expose SQLAlchemy models as a json:api webservice. This is demonstrated in the mini_app.py example.

In this app, an SQLa model class, named User, is created:

class User(SAFRSBase, db.Model):
    """
        description: User description
    """

    __tablename__ = "Users"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    email = db.Column(db.String)

A function create_api calls SAFRSAPI which creates a flask-restful API instance. The expose_object method creates the API endpoints and generates the API documentation for the User class.

def create_api(app, HOST="localhost", PORT=5000, API_PREFIX=""):
    api = SAFRSAPI(app, host=HOST, port=PORT, prefix=API_PREFIX)
    api.expose_object(User)
    user = User(name="test", email="[email protected]")

The rest of the code is a boilerplate Flask-SQLAlchemy app.

Implementation and Customization Notes

  • Columns with an underscore prefix(_) won't be exposed
  • You may override SAFRSBase methods to customize serialization and deserialization (see Customization)
  • Objects are automatically commited, this can be disable by using the SAFRSBase.db_commit class property
  • Instead of using multiple inheritance, you may create an abstract superclass
class BaseModel(safrs.SAFRSBase, db.Model):
    __abstract__ = True