Flask REST APIs in 5 Minutes complemented by AI Model from hugging face Part 1.

How to build your AI model interface through REST API in flask

Anderies
4 min readSep 27, 2021

i have been learning AI especially the computer vision part and wondering how to deploy the AI models, deploy in here the model can be used in any interface such as Mobile App, Web App, Desktop and even IOT Device.

Usually in my master's degree we as student just focuses on training and building the ML/DL model but never made it to the production. so after several research on how to deploy AI Models, I found python-flask, one of the most popular lightweight frameworks after Django. flask able to build AI Model interface through API.

REST API Consume by Interface

so i decided to write this article on how to make REST API in flask with a very simple approach which is only JSON Object and not related to database. in addition with loaded sentiment analysis AI Model.

note : if you want use database checkout flask-sqlalchemy or mysql.

In this article you will learn :

  1. How to make API Interface in REST Vocab about tweets
  2. How to do automatic sentiment analysis the tweets content
  3. How to build your AI model interface through API

first let’s make REST API, REST full vocab in here simply to say CRUD (Create Read Update Delete)

Installation & Setup

Before you start make sure you have :

  1. Postman, Pip, Python
  2. Flask, Pytorch, Transformers Library

make sure you have pip and python and then install flask :

pip install flask

the above code to install flask to build our AI model API interface

create file main.py and then copy/type code below to test that everything is working:

# import objects from the Flask model
from flask import Flask, jsonify, request
# declare flask
app = Flask(__name__) # define app using Flask
@app.route('/', methods=['GET'])
def test():
return jsonify({'message': 'It works!'})

after that try to use python main.py command to run the application and test it using postman application: https://www.postman.com/

  1. (GET Verb) Request to get all tweets and single tweets based on date path parameters
tweets = [{'content': 'dont know what todo', 'date': '17-02-2021', 'id': '1'},{'content': 'doing flask', 'date': '18-02-2021', 'id': '2'}]@app.route('/tweet', methods=['GET'])
def returnAll():
return jsonify({'tweets': tweets})
@app.route('/tweet/<string:date>', methods=['GET'])
def returnOne(date):
tweet = [t for t in tweets if t['date'] == date]
return jsonify({'data': tweet[0]})

2. (POST Verb) request to post or create the tweets

@app.route('/tweet', methods=['POST'])def createTweet():
tweet = {'content': request.json['content'],'date': request.json['date'], 'id': request.json['id']}
tweets.append(tweet)
return jsonify({'data': tweet})

3. (PUT Verb) request to update or edit the tweets content

@app.route('/tweet/<string:id>', methods=['PUT'])
def editOne(id):
tweet = [t for t in tweets if t['id'] == id]
tweet[0]['content'] = request.json['content']
return jsonify({'data': tweet[0]})

4. (Delete Verb) request to remove the tweets content based on ID

@app.route('/delete-tweet/<string:id>', methods=['DELETE'])
def removeOne(id):
tweet = [t for t in tweets if t['id'] == id]
tweets.remove(tweet[0])
return jsonify({'tweets': tweets})

after created the CRUD operations for our tweets object let’s make load the sentiment analysis model and perform automatic sentiment in tweets content and test it out using postman

5. (Loaded Sentiment Analysis DistilBert Model)

i’m not going to train, tuning and etc the model because isn’t the tutorial about i will just go download the sentiment model to predict whether the tweets positive or negative here: https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/tree/main

AI Model API

in the above, if you see carefully the response of sentiment attribute is changed based on the post request of content you send and the API is able to identify the sentences whether it’s negative or positive.

to build AI Model API, you need to install PyTorch and transformers and then copy/type the code below:

from flask import Flask, jsonify, request  
# import objects from the Flask model
from keras.models import load_model
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TextClassificationPipeline
app = Flask(__name__) # define app using Flasktokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")pipe = TextClassificationPipeline(model=model, tokenizer=tokenizer)

and change the post request in the route @app.route(‘/tweet’, methods=[‘POST’]) like this :

@app.route('/tweet', methods=['POST'])
def createTweet():
content = request.json['content']
hasil = pipe(content)
tweet = {'content': content,'date': request.json['date'], 'id': request.json['id'], 'sentiment': hasil[0]['label']}
tweets.append(tweet)
return jsonify({'data': tweet})

actually, there’s many ways of load the AI model depends on the type of model such as load_model by keras

Here’s is the full code access in my Github link: https://github.com/Anderies/flask-simple-rest

in the upcoming part 2 tutorial, I will try to code a web or mobile interface for using this AI model API.

This post is made by purpose to sharing my knowledge and looking for room of improvement, want to be criticized, if you have your own Thought or ideas don’t hesitate to share on the comment below!

if you have any questions about the articles just send me the message I’d love to answer it ✌️

LN: https://www.linkedin.com/in/anderies-notanto/

Web: anderies.web.app

And as usual, if you liked this article, hit that clap button below see you on the next post👏

--

--