Create your first REST API

The module provides helpers to build a REST API based on a function which computes predictions for a machine learning model. The following steps explains how to build a simple example.

Train a model

Let’s train and save a simple model based on Iris datasets.


import pickle
from sklearn import datasets
from sklearn.linear_model import LogisticRegression

iris = datasets.load_iris()
X =[:, :2]  # we only take the first two features.
y =
clf = LogisticRegression(), y)
with open("iris2.pickle", "wb") as f:
    pickle.dump(clf, f)


    /usr/local/lib/python3.7/site-packages/sklearn/linear_model/ FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
    /usr/local/lib/python3.7/site-packages/sklearn/linear_model/ FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning.
      "this warning.", FutureWarning)

The model could be anything not from scikit-learn or any other machine learning library not even a model.

Implement your predict function

The following function must be stored in a local file. Let’s choose


import pickle

# We declare an id for the REST API.

def restapi_version():
    return "0.1.1234"

# We declare a loading function.

def restapi_load():
    with open("iris2.pickle", "rb") as f:
        loaded_model = pickle.load(f)
    return loaded_model

# We declare a predict function.

def restapi_predict(clf, X):
    return clf.predict_proba(X)

# We test it works.
if __name__ == "__main__":
    clf = restapi_load()
    print(restapi_predict(clf, [0.1, 0.2]))



Start the REST API server

We first run the server locally. The command line cmd_start_mlrestapi_cmd:

start_mlrestapi --name=dummyfct

Test the REST API

The final test consists in checking we can obtain the prediction by calling the server.

import requests
import ujson
features = ujson.dumps({'X': [0.1, 0.2]})
r ='', data=features)

REST API with authentification

To query the REST API with an authentified user:

import requests
import ujson
features = ujson.dumps({'X': [0.1, 0.2]})
r ='', data=features, protocol='https',
                  headers=dict(uid="user", token="password"))

The command line cmd_start_mlrestapi_cmd can launch the application which requires authentification:

start_mlrestapi --name=dummyfct --users=encrypted_passwords.txt

There is an first step which consists in encrypting the password with command cmd_encrypt4mlrestapi_cmd.

encrypt_pwd --input=users.txt --output=encrypted_passwords.txt