-
Notifications
You must be signed in to change notification settings - Fork 4
Creating API endpoints
Gonrin edited this page Jun 5, 2018
·
4 revisions
To use this extension, you must have defined your database models using either SQLAlchemy or Gatco-SQLALchemy.
The basic setup for Gatco-SQLAlchemy is the same. First, create your gatco.Gatco object, gatco_sqlalchemy.SQLAlchemy object, and model classes as usual but with the following two (reasonable) restrictions on models:
- They must have a primary key column of type sqlalchemy.Integer or type sqlalchemy.Unicode or type sqlalchemy.dialects.postgresql.UUID
- They must have an init method which accepts keyword arguments for all columns. (the constructor in gatco_sqlalchemy.SQLAlchemy.Model supplies such a method, so you don’t need to declare a new one).
from gatco import Gatco
from gatco_sqlalchemy import SQLAlchemy
from gatco_restapi import APIManager
# Create the Gatco application and the Gatco-SQLAlchemy object.
app = Gatco(name=__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['SECRET_KEY'] = 'secret'
app.config['SESSION_COOKIE_SALT'] = 'salt_key'
db = SQLAlchemy()
db.init_app(app)
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
birth_date = db.Column(db.Date)
computers = db.relationship('Computer')
class Computer(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
vendor = db.Column(db.Unicode)
purchase_time = db.Column(db.DateTime)
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
owner = db.relationship('Person')
# Create the database tables.
db.create_all()
Second, instantiate a gatco_restapi.APIManager object with the Gatco and SQLAlchemy objects:
from import gatco_restapi import APIManager
manager = APIManager(app, sqlalchemy_db=db)
Third, create api endpoint:
manager.create_api(Person,
methods=['GET', 'POST', 'DELETE', 'PUT'],
url_prefix='/api/v1',
preprocess={
"GET_SINGLE": [pre_get_single_func],
"GET_MANY": [pre_get_many_func],
"POST": [pre_post_func],
"PUT_SINGLE": [pre_put_func]
},
postprocess= dict(GET_MANY=[post_get_many_func]),
#exclude_columns = ['birth_date'],
include_columns = ['id','name','birth_date'],
collection_name='person'
)
manager.create_api(Computer)
Forth, start the Gatco loop
app.run(host="0.0.0.0", port=8000)