Saturday, May 23, 2020

Building REST APIs with FLASK Python Web Services -Database Modeling in FLASK

Database Modeling in FLASK

So now let's have a look at Database's most important aspect of REST application development.FLASK being a microframework provides facility to connect with different types of
databases like SQL and NoSql based database in FLASK. You can also connect with ORM types.

Creating a FLASK Application with SQLAlchemy

FLASK-SQLAlchemy is an extension for FLASK which adds support for SQLAlchemy to the application.SQLAlchemy is a python toolkit and ORM that provides access to the SQL database
using Python.FLASK-SQLAlchemy provides support for the following SQL based database engines gives the appropriate DBAPI driver is installed:

1) PostgreSQL
2)MYSQL
3)ORACLE
4)SQLite
5)Microsoft SQL Server
6)Firebird Sybase 

Anyways we will use MySql so let's create a new directory called flask-MySQL, create a virtual environment and then install flask-sqlalchemy.
  
  $mdir flask-mysql && cd flask-mysql
  
Now create a virtual environment inside the directory using the following commands
  
   $virtualenv venv
   
Once the virtualenv is activated.lets install flask-sqlalchemy.FLASK and FLASK-SQLAlchemy can be installed using PIP commands.

   (venv)$ pip install flask-sqlalchemy

Now let's install PyMySQl to enable MySQL connection with FLASK-SQLAlchemy.

   (venv)$ pip install pymysql

   
 Now we have everything we need to create our sample flask-mysql application. Let's name the file as app.py which will contain the code for our application.

Code :

from flask import Flask
from flask-sqlalchemy import SQLAlchemy


app = FLASK(_name_) 
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql:<mysql_username>:<mysql_password>@<mysql_host>:<mysql_port>/<mysql_db>'
db = SQLAlchemy(app)

if _name_ == "_name_":
    app.run(debug=True)
Creating an Author Database

 class Author(db.Model):
      id = db.Column(db.Integer,primary_key=True)
  name = db.Column(db.String(20))
  specelisation = db.Column(db.String(50))
  
  def _init_(self,name,specelisation):
      self.name=name
  self.specelisation = specelisation
  
      def _repr_(self):
     return '<product %d>' % self.id
 
  db.create_all()

With this code we have created a model titled "Author" which has three fields. Okay now there import thing before move ahead like in order to serve JSON response from our API using 
the data returned by SQLAlchemy we need another library called marshmallow which is an addon to SQLAlchemy to serialize SQLAlchemy-returned data objects to JSON.

  (venv)$ pip install flask-marshmallow

We will define our schema from the Author model using marshmallow.

from marshmallow_sqlalchemy import ModelSchema
from marshmallow import fields

After db.create_all() define your output schema using the following code:

   class Author(ModelSchema):
      class Meta(ModelSchema.Meta):
           model = Author
           sql_session = db.session
   
      id = feilds.Number(dump_only=True)
  name = feilds.String(required=True)
  specelisation = feilds.String(required=True)
  
So this maps the fields to the variables attribute to feild objects and in Meta we define the Model to relate to our schema. So this will help us return JSON from SQLAlchemy.

Before writing the endpoints edit the first import line to the following to import jsonify, make_response, and request from FLASK.

from flask import Flask, request,jsonify,make_response

And after the AuthorSchema write your first endpoint/authors with follwoing code:

@app.route('/authors' , methods = ['GET'])
def index():
    get_authors = Author.query.all()
author_schema = AuthorSchema(many=true)
authors,error = author_schema.dump(get_authors)
return make_response(jsonify({"authors: authors"}))
In this method we are fetching all the authors in the DB dumping it in the AuthorSchema and returning the result in JSON.
Run the application using Python app.py and then query the endpoint using your preferred REST client. I will be using POSTMAN to request the endpoint.
So just open your POSTMAN and the http://localhost:5000/authors to query the endpoint.











1 comment:

Anonymous said...

Awesome.Rare to find.