In previous article we have seen normal Rest API with python and Flask which stores information into list and retrive data from list. So in this article we are going to build REST API with flask and SQLAlchemy and Marshmallow libraries with Sqlite database.
First of all Let’s learn something about SQLAlchemy and marshmallow
SQLAlchemy is python SQL toolkit and ORM (Object relational mapping) that gives developer the full power and flexibility of SQL. Where flask-sqlalchemy is flask extension that adds support for SQLAlchemy to flask application.
Reference : https://www.sqlalchemy.org/ , https://flask-sqlalchemy.palletsprojects.com/en/2.x/
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.
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 set virtual environment for your flask api project.
# create virtaul environment python3 -m venv env # activate virtual envionment source env/bin/activate # install flask pip install flask # install Flask-SQLAlchemy pip install flask_sqlalchemy # install Flask-Marshmallow pip install flask_marshmallow # install marshmallow-sqlalchemy pip install marshmallow-sqlalchemy
Once all setup is done , create one python file app.py and we are going to learn step by step process to write API in flask.
First, we will write all required import statements
from flask import Flask,request,jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow import os
Second, We are initializing our flask app and setting db location for SQLAlchemy and generate object for SQLAlchemy and marshmallow
app = Flask(__name__) basedir = os.path.abspath(os.path.dirname(__file__)) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,'curd.sqlite') db = SQLAlchemy(app) ma = Marshmallow(app)
After that we are going to make one Model class for User which has id , username and email as their columns and below we have defined structure of response of our endpoint. We have defined user_schema as instance of UserSchema and Users_schema as instance of UserSchema with multiple fields.
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80),unique=True) email = db.Column(db.String(120),unique=True) def __init__(self,username,email): self.username = username self.email = email class UserSchema(ma.Schema): class Meta: fields = ('username','email') user_schema = UserSchema() users_schema = UserSchema(many=True)
Now we are ready to set routes for our endpoint so let’s first make our first end point which has route to “/user” and HTTP method as POST, which can we used for adding new Users into our database.
@app.route("/user", methods=["POST"]) def add_user(): username = request.json['username'] email = request.json['email'] new_user = User(username,email) db.session.add(new_user) db.session.commit() return jsonify(new_user)
Another end point which has Route “/user” but with GET as HTTP method, which can be used as getting users list.
@app.route("/user", methods=["GET"]) def get_user(): all_users = User.query.all() result = users_schema.dump(all_users) return jsonify(result)
In this part we are going to define route as “/user/<id>” with HTTP method as GET , which can be used to get particular users details by passing Id as an argument.
@app.route("/user/<id>", methods = ["GET"]) def user_detail(id): user = User.query.get(id) return user_schema.jsonify(user)
Below is code snippet for updating users information by passing id in route “/user/<id>” with PUT as HTTP method.
@app.route("/user/<id>", methods = ["PUT"]) def user_update(id): user = User.query.get(id) username = request.json['username'] email = request.json['email'] user.email = email user.username = username db.session.commit() return user_schema.jsonify(user)
Lastly, We have route which can be used for DELETE user from database with Id passed in end point and HTTP method DELETE
@app.route("/user/<id>",methods = ["DELETE"]) def user_delete(id): user = User.query.get(id) db.session.delete(user) db.session.commit() return user_schema.jsonify(user)
That’s it. We have added all required code for adding , updating , deleting and selecting users from database. Now let’s make entry point for this code
if __name__ == "__main__": app.run(debug=True)
So, Once we have our code is ready , first of all we need to initialize database by running below code
# run python within your virtual environment python # import db and create database from app import db db.create_all()
Great, So we are all set to run our application, Let’s run server by running below command in your terminal.
# run flask server python3 app.py
So this will start flask server with port 5000 and it can be accessible with http://127.0.0.1:5000/users and we can now use POSTMAN for running API with POST , GET , PUT and DELETE functions.
Complete code for this tutorial can be found below