2. About this Presetation
• This guide will walk you through building a Restful APi with Flask . At
the end, you'll build a simple Crud APIs. The API will have endpoints
that can be used to add user, view users, update user, delete user &
view user.
3. At the end , following endpints will be available:
• GET - /user => Retrieve all users
• POST - /user - Add a new user
• GET - /user/<id> - get single user by id
• PUT - /user/<id> - Update a user
• DELETE - /user/<id> - Delete a user
4. Install Python
Debian or Ubuntu
> sudo apt install python3
Fedora
> sudo dnf install python3
Opensuse
> sudo zypper install python3
Windows:
Download latest python from python.org and install it
Verify Version
> python3 --version
it will show version like : Python 3.6.1
5. Install virtualenv
virtualenv is a virtual Python environment builder. It helps a user to
create multiple Python environments side-by-side. Thereby, it can avoid
compatibility issues between the different versions of the libraries.
The following command installs virtualenv
pip install virtualenv
or
Sudo apt-get install virtualenv
6. Create and Run Virtual Env
• Once installed, new virtual environment is created in a folder.
>mkdir newproj
>cd newproj
>virtualenv venv
• To activate corresponding environment, on Linux/OS X, use the following −
> venv/bin/activate
• On Windows, following can be used
> venvscriptsactivate
7. Install Flask
> pip install Flask
# pip is a package manager in python, it will available bydefault once
you install python
8. “Hello World” In Flask
• create a file index.py with following code:
> python index.py
now run on http://localhost:5000 (5000 is default port you may change
it)
9. Installing flask-sqlalchemy and flask-marshmallow
• SQLAlchemy is python SQL toolkit and ORM that gives developer the
full power and flexibility of SQL. Where flask-sqlalchemy is flask
extension that adds support for SQLAlchemy to flask
application(http://flask-sqlalchemy.pocoo.org/2.1/).
• In other hand flask-marshmallow is flask extension to integrate flask
with marshmallow(an object serialization/deserialization library). In
this presentation we use flask-marshmallow to rendered json
response
Turn next to install above
11. Create a Api.py with following code
//code
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
//code
Description : On this part we import all module that needed by our application.
We import Flask to create instance of web application, request to get request
data, jsonify to turns the JSON output into a Response object with the
application/json mimetype, SQAlchemy from flask_sqlalchemy to accessing
database, and Marshmallow from flask_marshmallow to serialized object.
12. CreateInstance & Set Sqlite Path and flask object
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,
'api.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)
Create a app instance and set sqlite path in app config,after it binding SQLAlchemy
and Marshmallow into our flask application.
13. Declare Model Class and constructor
//code
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
//code
14. Create a Response Schema
//code
class UserSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('id','username', 'email')
user_schema = UserSchema()
users_schema = UserSchema(many=True)
//code
//This part defined structure of response of our endpoint. We want that all of our endpoint will have JSON
response. Here we define that our JSON response will have 3 keys(id, username, and email). Also we defined
user_schema as instance of UserSchema, and user_schemas as instances of list of UserSchema.
15. Create a New User Api
# endpoint to create new user
//code
@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 user_schema.jsonify(new_user)
//code
On this part we define endpoint to create new user. First we set the route to “/user” and set HTTP methods to POST. After set the route
and methods we define function that will executed if we access this endpoint. On this function first we get username and email from
request data. After that we create new user using data from request data. Last we add new user to data base and show new user in JSON
form as response.
16. Show All users Api
# endpoint to show all users
//code
@app.route("/user", methods=["GET"])
def get_user():
all_users = User.query.all()
result = users_schema.dump(all_users)
return jsonify(result.data)
//code
//On this part we define endpoint to get list of all users and show the result as
JSON response.
17. View user Api
# endpoint to get user detail by id
//code
@app.route("/user/<id>", methods=["GET"])
def user_detail(id):
user = User.query.get(id)
return user_schema.jsonify(user)
//code
//on this part we define endpoint to get user data, but instead of get all the
user here we just get data from one user based on id. If you look carefully at the
route, you can see different pattern on the route of this endpoint. Patern like
“<id>” is parameter, so you can change it with everything you want. This
parameter should put on function parameter(in this case def user_detail(id)) so
we can get this parameter value inside function.
18. Update User Api
# endpoint to update user
//code
@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)
//code
we define endpoint to update user. First we call user that related with given id on parameter. Then we update username and email value
of this user with value from request data using put method.
19. Delete user Api
# endpoint to delete user
//code
@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)
//code
#endpoint to delete user. First we call user that related with given id on
parameter. Then we delete it.
20. Before Running Actions Now
• enter into python interactive shell using following command in your
terminal:
> python
• import db object and generate SQLite database
Use following code in python interactive shell
> from api import db
> db.create_all()
Api.sqlite will be generated inside your project folder
21. Run Application
> python crud.py
Now apis are in action , try via postman
Screenshot Attached in Next Slide