Just starting off with Flask, following along at http://flask.pocoo.org/docs/views/
Say I have a basic REST api, in this case for symptoms:
/
GET - list
POST - create
/<symptomid>
GET - detail
PUT - replace
PATCH - patch
DELETE - delete
I can implement this pretty cleanly with Flask’s MethodView as follows:
from flask import Blueprint, request, g
from flask.views import MethodView
#...
mod = Blueprint('api', __name__, url_prefix='/api')
class SymptomAPI(MethodView):
""" ... """
url = "/symptoms/"
def get(self, uid):
if uid is None:
return self.list()
else:
return self.detail(uid)
def list(self):
# ...
def post(self):
# ...
def detail(self, uid):
# ...
def put(self, uid):
# ...
def patch(self, uid):
# ...
def delete(self, uid):
# ...
@classmethod
def register(cls, mod):
symfunc = cls.as_view("symptom_api")
mod.add_url_rule(cls.url, defaults={"uid": None}, view_func=symfunc,
methods=["GET"])
mod.add_url_rule(cls.url, view_func=symfunc, methods=["POST"])
mod.add_url_rule('%s<int:uid>' % cls.url, view_func=symfunc,
methods=['GET', 'PUT', 'PATCH', 'DELETE'])
SymptomAPI.register(mod)
But, let’s say I would like to attach another api on these individual symptoms:
/<symptomid>/diagnoses/
GET - list diags for symptom
POST - {id: diagid} - create relation with diagnosis
/<symptomid>/diagnoses/<diagnosisid>
GET - probability symptom given diag
PUT - update probability of symptom given diag
DELETE - remove diag - symptom relation
I would then have 4 GETs instead of two as above.
- Do you think this a bad api design?
- Would
MethodViewbe appropriate for this design? (if the design is not bad) - How would you implement these routes?
So … in writing this question, I have found a decent solution. As long as I’m here, I might as well post the question and the solution I have. Any feedback would still be greatly appreciated.
I think the design is ok.
MethodViewshould be pretty awesome for it. You can put the routes together like so: