In this Flask Tutorial we are going to learn how to Build REST API with Python Flask & SQLAlchemy.
What is SQLAlchemy ?
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. It provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.
What is Flask-SQLAlchemy ?
Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy with Flask by providing useful defaults and extra helpers that make it easier to accomplish common tasks. See the SQLAlchemy documentation to learn how to work with the ORM in depth.
What is Marshmallow ?
Marshmallow is an ORM/ODM/framework-agnostic library for converting complex data types, such as objects, to and from native Python data types.
Marshmallow schemas can be used to:
- Validate input data.
- De-serialize input data to app-level objects.
- Serialize app-level objects to primitive Python types. The serialized objects can then be rendered to standard formats such as JSON for use in an HTTP API.
What is Flask-Marshmallow ?
Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy.
First of all we need to install these libraries.
1 2 3 4 5 6 7 8 9 10 11 |
# install flask pip install flask # install Flask-SQLAlchemy pip install flask_sqlalchemy # install Flask-Marshmallow pip install flask_marshmallow #for mysql db install this pip install mysqlclient |
So now this is the complete code for Build REST API with Python Flask & SQLAlchemy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow #initliazing our flask app, SQLAlchemy and Marshmallow app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:''@localhost/post' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ma = Marshmallow(app) #this is our database model class Post(db.Model): id = db.Column(db.Integer, primary_key = True) title = db.Column(db.String(100)) description = db.Column(db.String(200)) author = db.Column(db.String(50)) def __init__(self, title, description, author): self.title = title self.description = description self.author = author class PostSchema(ma.Schema): class Meta: fields = ("title", "author", "description") post_schema = PostSchema() posts_schema = PostSchema(many=True) #adding a post @app.route('/post', methods = ['POST']) def add_post(): title = request.json['title'] description = request.json['description'] author = request.json['author'] my_posts = Post(title, description, author) db.session.add(my_posts) db.session.commit() return post_schema.jsonify(my_posts) #getting posts @app.route('/get', methods = ['GET']) def get_post(): all_posts = Post.query.all() result = posts_schema.dump(all_posts) return jsonify(result) #getting particular post @app.route('/post_details/<id>/', methods = ['GET']) def post_details(id): post = Post.query.get(id) return post_schema.jsonify(post) #updating post @app.route('/post_update/<id>/', methods = ['PUT']) def post_update(id): post = Post.query.get(id) title = request.json['title'] description = request.json['description'] author = request.json['author'] post.title = title post.description = description post.author = author db.session.commit() return post_schema.jsonify(post) #deleting post @app.route('/post_delete/<id>/', methods = ['DELETE']) def post_delete(id): post = Post.query.get(id) db.session.delete(post) db.session.commit() return post_schema.jsonify(post) if __name__ == "__main__": app.run(debug=True) |
OK in the above code, this is our database configuration iam using MySQL database, and also iam using Wamp Server for this. we are initializing our flask app, also we need to create the object for SQLAlchemy and Marshmallow.
1 2 3 4 5 6 7 8 |
app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:''@localhost/post' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ma = Marshmallow(app) |
After that we are going to make one Post class for our posts model which has id , title, description and author as their columns and below we have defined structure of response of our endpoint. We have defined post_schema as instance of PostSchema and posts_schema as instance of PostSchema with multiple fields.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Post(db.Model): id = db.Column(db.Integer, primary_key = True) title = db.Column(db.String(100)) description = db.Column(db.String(200)) author = db.Column(db.String(50)) def __init__(self, title, description, author): self.title = title self.description = description self.author = author class PostSchema(ma.Schema): class Meta: fields = ("title", "author", "description") post_schema = PostSchema() posts_schema = PostSchema(many=True) |