In this article i want to show you How to Build REST API with SQLAlchemy & Marshmallow, basically we are using SQLAlchemy & Marshmallow for Building REST API in Flask. also you can watch the complete video for this article at the end.
Also Check this article
Build Complete CRUD Application With FLASK & SQLAlchemy
What is Flask ?
Flask is a web framework. This means flask provides you with tools, libraries and technologies that allow you to build a web application. This web application can be some web pages, a blog, a wiki or go as big as a web-based calendar application or a commercial website.
Flask is part of the categories of the micro-framework. Micro-framework are normally framework with little to no dependencies to external libraries. This has pros and cons. Pros would be that the framework is light, there are little dependency to update and watch for security bugs, cons is that some time you will have to do more work by yourself or increase yourself the list of dependencies by adding plugins.
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. The following documentation is a brief overview of the most common tasks, as well as the features specific to Flask-SQLAlchemy.
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.
Installation
1 2 3 4 5 6 7 8 |
# install flask pip install flask # install Flask-SQLAlchemy pip install flask_sqlalchemy # install Flask-Marshmallow pip install flask_marshmallow |
So now this is the complete code for How to Build REST API with SQLAlchemy & Marshmallow
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) |
OK Now we are going to set routes for our endpoint so let’s first make our first end point which has route to “/post” and HTTP method as POST, which can we used for adding new Posts into our database.
1 2 3 4 5 6 7 8 9 10 11 |
@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) |
And these routes are for getting the post, updating the post , deleting the post and getting a particular post
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 |
@app.route('/get', methods = ['GET']) def get_post(): all_posts = Post.query.all() result = posts_schema.dump(all_posts) return jsonify(result) @app.route('/post_details/<id>/', methods = ['GET']) def post_details(id): post = Post.query.get(id) return post_schema.jsonify(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) @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) |
That’s it. We have added all required code for adding , updating , deleting and selecting of our Post model, now your can run your flask application, if you see the video for this article iam using Postman for checking of my endpoints.
Also you can watch the complete video for this article
Subscribe and Get Free Video Courses & Articles in your Email