In this tutorial we will see how you can make your first REST API for Machine Learning Model using FLASK. We will start by creating machine learning model. Then we will see step-by-step procedure to create API using Flask and test it using Postman. Part 1: Creating Machine Learning Model The first thing we will need is to import the necessary libraries. After importing necessary libraries we will need to import data. In this project we will be using Boston Housing data set and it can be downloaded from . sklearn.datasets pandas pd numpy np matplotlib.pyplot plt seaborn sns sklearn metrics sklearn.datasets load_boston boston_data = load_boston() data_ = pd.DataFrame(boston_data.data) data_.head() # importing necessary libraries import as import as import as import as from import # importing dataset from sklearn from import # initializing dataset ### Top five rows of dataset Currently our data set does not have any feature name. So we will need to import feature name for the data set. data_.columns = boston_data.feature_names data_.head() # Adding features names to the dataframe Pre-processing the data The variable we want to predict is price. So we will now create target variable for our Machine Learning Model. data_[ ] = boston_data.target # Target feature of Boston Housing data 'PRICE' Now, we will check if any of our features are null and categorical or not. This is because null values would result in biased estimation machine learning models requires numerical values rather than categorical. data_.isnull().sum() # checking null values No null values are found so features are left as it is. Now let's check if there are any categorical values. data_.info() # checking if values are categorical or not We can see that all features are numerical. So now we will now create our model. Creating model At first we will need to separate feature and target variable. Then split data set into training and testing set. And finally create a model. X = data_.drop([ ], axis= ) y = data_[ ] sklearn.model_selection train_test_split X_train, X_test, y_train, y_test = train_test_split(X,y,test_size= , random_state= ) print( , X_train.shape ) print( , X_test.shape ) print( y test shape :”, y_test.shape ) sklearn.ensemble RandomForestRegressor classifier = RandomForestRegressor() classifier.fit(X_train, y_train) # creating feature and target variable 'PRICE' 1 'PRICE' # splitting into training and testing set from import 0.2 1 "X training shape : " "X test shape : " "y training shape :“ , y_train.shape ) print(" # creating model from import Now let's evaluate the performance of model for training and testing set. prediction = classifier.predict(X_train) print( , metrics.r2_score(y_train, prediction)) print( , metrics.mean_absolute_error(y_train, prediction)) print( , metrics.mean_squared_error(y_train, prediction)) print( , np.sqrt(metrics.mean_squared_error(y_train, prediction))) prediction_test = classifier.predict(X_test) print( , metrics.r2_score(y_test, prediction_test)) print( , metrics.mean_absolute_error(y_test, prediction_test)) print( , metrics.mean_squared_error(y_test, prediction_test)) print( , np.sqrt(metrics.mean_squared_error(y_test, prediction_test))) # Model evaluation for training data "r^2 : " "Mean Absolute Error: " "Mean Squared Error: " "Root Mean Squared Error : " # Model evaluation for testing data "r^2 : " "Mean Absolute Error : " "Mean Squared Error : " "Root Mean Absolute Error : " Part 2: Saving and using machine learning model We will use for saving model. Serialization and DeSerialization mechanism helps to save the machine learning object model into byte stream and vice versa. The model will be saved under folder. The working structure of the project is shown in Part 3. pickle model pickle open( , ) file: pickle.dump(classifier, file) model_columns = list(X.columns) open( , ) file: pickle.dump(model_columns, file) # saving the model import with 'model/model.pkl' 'wb' as # saving the columns with 'model/model_columns.pkl' 'wb' as Part 3: Creating API for machine learning using Flask After successfully creating machine learning model. We will need to create a web-sever in Flask. Flask is lightweight web application which is easy to use and scale up to complex application. This tutorial covers the basic implementation of Flask application i.e. making a web server and simple REST API. Here is how the whole project is organized: To use Flask, first create a folder name and install flask inside it using following command in terminal. Make sure flask is inside folder. webapp webapp >> pip install Flask A minimal web-application can be produced using Flask. The following code will create a simple web-app that redirects to stated URL to produce given results. flask Flask app = Flask(__name__) __main__ from import @app.route('/', methods=['GET', 'POST']) : def main () return "Boston House Price Prediction” if __name__ == " ": app.run() Running the app To start flask server on local machine, navigate to webapp folder and run the command in terminal. >> export FLASK_APP=app.py >> export FLASK_ENV=development >> flask run This will execute the application. Now navigate to web browser ( ) to see the result. The final result is shows below: localhost:5000 Let's put all the code together to check if we missed anything or not. All files are separated into files. So the complete file should look like: .py app.py flask render_template, request, jsonify flask numpy np traceback pickle pandas pd app = Flask(__name__,template_folder= ) open( , ) f: classifier = pickle.load (f) open( , ) f: model_columns = pickle.load (f) flask.request.method == : flask.request.method == : : json_ = request.json print(json_) query_ = pd.get_dummies(pd.DataFrame(json_)) query = query_.reindex(columns = model_columns, fill_value= ) prediction = list(classifier.predict(query)) jsonify({ :str(prediction) }) : jsonify({ : traceback.format_exc() }) __name__ == : app.run() from import import import as import import import as # App definition 'templates' # importing models with 'webapp/model/model.pkl' 'rb' as with 'webapp/model/model_columns.pkl' 'rb' as @app.route('/') : def welcome () return "Boston Housing Price Prediction" @app.route('/predict', methods=['POST','GET']) : def predict () if 'GET' return "Prediction page" if 'POST' try 0 return "prediction" except return "trace" if "__main__" Part 4: Testing API in Postman To test our API we will need API client and we will be using Postman. Once you have download Postman it should look like this. Now we will type our URL ( ) and type required features our model in . format inside Body. And change request type to POST. Our final result should look like this. localhost:5000/predict json Summary By this point, you have developed Machine Learning and used Flask to create API, which can be used to predict the price of houses in Boston. Extending this work This article focuses on creating REST API for Machine Learning model and testing on Postman. Further it can be extended to make web-application and deploy in Heroku cloud platform.