There are times when you want to quickly create a small API while using a DB. In that case, Flask is convenient. Basically, you can create an API just by fleshing out the following code.
In my opinion, if you have a medium-sized project, add flask- * later, or use a lot of DB, you should use a framework such as Django. If you plan to move to another framework later, use that one.
The API that provides CRD for Model is shown below. (Update will be implemented later if you feel like it)
# coding: utf-8
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@localhost/postgres'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
# Model
class Model(db.Model):
__tablename__ = 'models'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
def to_dict(self):
return dict(
id=self.id,
name=self.name
)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Model {}>'.format(self.name)
@app.route("/api/v1/model/<id>", methods=['DELETE'])
def api_v1_model_id(id):
if request.method == 'DELETE':
d = Model.query.get(id)
db.session.delete(d)
db.session.commit()
return '', 204
@app.route("/api/v1/models", methods=['GET', 'POST'])
def api_v1_models():
if request.method == 'POST':
name = request.json['name']
d = Model(name)
db.session.add(d)
db.session.commit()
return jsonify(d.to_dict()), 201
if request.method == 'GET':
ls = Model.query.all()
ls = [l.to_dict() for l in ls]
return jsonify(ls), 200
if __name__ == "__main__":
db.drop_all()
db.create_all()
app.run(host='0.0.0.0', port=3001)
Recommended Posts