Advertisement
  1. Code
  2. Coding Fundamentals
  3. Rest API

Building RESTful APIs With Flask: ORM Independent

Scroll to top
Read Time: 3 min
This post is part of a series called Building RESTful APIs With Flask.
Building RESTful APIs With Flask: An ORM With SQLAlchemy

In the first part of this three-part tutorial series, we saw how to write RESTful APIs all by ourselves using Flask as the web framework. In the second part, we created a RESTful API using Flask-Restless, which depends on SQLAlchemy as the ORM. In this part, we will use another Flask extension, Flask-Restful, which abstracts your ORM and does not make any assumptions about it. 

I will take the same sample application as in the last part of this series to maintain context and continuity. Although this example application is based on SQLAlchemy itself, this extension can be used along with any ORM in a similar fashion, as shown in this tutorial.

Installing Dependencies

While continuing with the application from the first part, we need to install only one dependency:

1
pip install Flask-Restful

The Application

Before we start, you might want to remove the code that we wrote for the second part of this tutorial series for more clarity.

As always, we will start with changes to our application's configuration, which will look something like the following lines of code: 

flask_app/my_app/__init__.py

1
from flask import Flask
2
from flask_restful import Api
3
4
5
app = Flask(__name__)
6
api = Api(app)

flask_app/my_app/product/views.py

1
import json
2
from flask import request, Blueprint, abort
3
from my_app import db, app,api
4
from my_app.product.models import Product
5
from flask_restful import Resource,reqparse
6
7
8
catalog = Blueprint('catalog', __name__)
9
10
parser = reqparse.RequestParser()
11
parser.add_argument('name', type=str)
12
parser.add_argument('price', type=float)
13
 
14
15
 
16
17
@catalog.route('/')
18
@catalog.route('/home')
19
def home():
20
    return "Welcome to the Catalog Home."
21
22
23
24
#FLASK RESTFUL ENDPOINTS

25
26
 
27
class ProductApi(Resource):
28
 
29
    def get(self, id=None, page=1):
30
        if not id:
31
            products = Product.query.paginate(page, 10).items
32
        else:
33
            products = [Product.query.get(id)]
34
        if not products:
35
            abort(404)
36
        res = {}
37
        for product in products:
38
            res[product.id] = {
39
                'name': product.name,
40
                'price': product.price,
41
            }
42
        return json.dumps(res)
43
 
44
    def post(self):
45
        args = parser.parse_args()
46
        name = args['name']
47
        price = args['price']
48
        product = Product(name, price)
49
        db.session.add(product)
50
        db.session.commit()
51
        res = {}
52
        res[product.id] = {
53
            'name': product.name,
54
            'price': product.price,
55
        }
56
        return json.dumps(res)
57
 
58
api.add_resource(
59
   ProductApi,
60
   '/api/product',
61
   '/api/product/<int:id>',
62
   '/api/product/<int:id>/<int:page>'
63
)
64

argparse is a library that makes it easy to validate form data in Flask.

Testing the Application

This application can be tested exactly as we did in the second part of this tutorial series. I have kept the routing URL the same for the same purpose.

Conclusion

In this last part of this three-part tutorial series on developing RESTful APIs with Flask, we saw how to write ORM-independent RESTful APIs. This wraps up the basics of writing RESTful APIs with Flask in various ways. 

There's more to learn about each of the methods covered, and you can explore this on your own, using the basics you've learned in this series.

This post has been updated with contributions from Esther Vaati. Esther is a software developer and writer for Envato Tuts+.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.