Creating a class-based REST interface
We saw how class-based views work in Flask using the concept of pluggable views in the Class-based views recipe in Chapter 4, Working with Views. We will now see how we can use the same concept to create views, which will provide a REST interface to our application.
Getting ready
Let's take a simple view that will handle the REST style calls to our Product
model.
How to do it…
We have to simply modify our views for product handling to extend the MethodView
class:
from flask.views import MethodView class ProductView(MethodView): def get(self, id=None, page=1): if not id: products = Product.query.paginate(page, 10).items res = {} for product in products: res[product.id] = { 'name': product.name, 'price': product.price, 'category': product.category.name } else: product = Product.query.filter_by(id=id...