I currently build a web application using flask, sqlalchemy and jinja2.
To get a proper web interface, I build my views as follows:
@app.route('/mydata/', methods=['GET'])
@login_required
def mydata_list():
# build data here...
return render_template('mydata/index.html', data=data))
Now, if I need to build a REST API, I am supposed to terminate with
return jsonify(data)
So, how to handle this to avoid code duplication? Is it a good practice to add a ?api=True
to my url, test it in my view, then return appropriate answer?
There is really no right or wrong way to do this, more so with Flask, which is a framework that imposes so few rules on the developer.
If you want my opinion, I think using the same set of view functions for web site and API leads to code that is harder to maintain, because there are a few significant differences between the two, for example:
DELETE
request. A web application running on a web browser needs to do everything with GET
and POST
requests. Also, the POST
request method has different usages in APIs vs. web apps.My recommendation is that you make your view functions for both APIs and web apps very thin and put the business logic of your application in common classes that both sets of view functions can invoke.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With