Basic Rest API in Flask and SqlAlchemy

  1. Step 1: pipenv install --python 3.8
  2. Step 2: pipenv shell
  3. Step 3: pipenv install flask flask-sqlalchemy flask-marshmallow marshmallow-sqlalchemy flask-migrate psycopg2

flask-sqlalchemy is the sql-alchemy with flask bindings. flask-marshmallow is like the Serializer in Django Rest Framework, marshmallow-sqlalchemy is common binding between marshmallow and sqlalchemy (for things like ModelSerializer in Django Rest Framework).flask-migrate is migration tool for Flask based on ALEMBIC.psycopg2-binary is for connecting to postgres db.

Note: If psycopg2 install gives errors use psycopg2-binary. But this is a development only binary. It is not meant for production. For production, you need to compile psycopg2 from source.
See here for installing psycopg2 if you face issues: https://tekshinobi.com/install-psycopg2-on-ubuntu-18-04/

Now create the application file.. traditionally called app.py (or main.py…whatever your taste).
touch app.py

Now do these steps on the console (don’t do the third step yet as app.py is still empty):

  1. export FLASK_APP=app.py
  2. export FLASK_ENV=development
  3. flask run

The no. 2 in above list is important. It will hot reload the server upon code changes

Here is the app.py file. This is a toy CRUD app. So, all code is in one file.

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os

# Init app
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# Database
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///' + os.path.join(basedir,'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init db
db = SQLAlchemy(app)
# Init marshmallow
ma = Marshmallow(app)

class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True)
    description = db.Column(db.String(200))
    price = db.Column(db.Float)
    qty = db.Column(db.Integer)

    def __init__(self, name, description, price, qty):
        self.name = name
        self.description = description
        self.price = price
        self.qty = qty

# Product Schema
class ProductSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name', 'description', 'price', 'qty')

#Init schema
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)


#Create a Route to add product
@app.route('/product', methods=['POST'])
def add_product():
    name = request.json['name']
    description = request.json['description']
    price = request.json['price']
    qty = request.json['qty']

    new_product = Product(name, description, price, qty)
    db.session.add(new_product)
    db.session.commit()
    return product_schema.jsonify(new_product)


# fetch all products
@app.route('/product', methods=['GET'])
def get_products():
    all_products = Product.query.all()
    result = products_schema.dump(all_products)
    return jsonify(result)

# fetch a product
@app.route('/product/<id>', methods=['GET'])
def get_product(id):
    product = Product.query.get(id)
    return product_schema.jsonify(product)

# update a product
@app.route('/product/<id>', methods=['PUT'])
def update_product(id):
    product = Product.query.get(id)
    name = request.json['name']
    description = request.json['description']
    price = request.json['price']
    qty = request.json['qty']

    product.name = name
    product.description = description
    product.price = price
    product.qty = qty

    db.session.commit()
    return product_schema.jsonify(product)


# delete a product
@app.route('/product/<id>', methods=['DELETE'])
def delete_product(id):
    product = Product.query.get(id)
    db.session.delete(product)
    db.session.commit()
    return product_schema.jsonify(product)
# Run Server
if __name__=='__main__':
    app.run(debug=True)

Before running this app, lets create the database and populate it.

Goto Python console and say:

>>>from app import db
>>>db.create_all()

Thats it. SQLAlchemy has done all the magic for you and created your database.

Now run the app by:
flask run




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *