Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices to combine REST API with web interface using FLASK

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?

like image 677
Nic Avatar asked Dec 27 '13 09:12

Nic


1 Answers

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:

  • Authentication: this is typically done in very different ways for web vs. API.
  • Content: for the API you just return data, but for a web page the view function may need to do more work and obtain extra data that is only needed for rendering the template.
  • Request methods: APIs use more HTTP request methods than web apps. For example, to delete a resource through an API the client normally sends a 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.

like image 162
Miguel Avatar answered Sep 28 '22 03:09

Miguel