Predictive Hacks

Python Rest API Example

pythom rest api example

Let’s assume that we are very good at creating machine learning models and we can make an image recognition algorithm and many different and interesting projects. What’s the next step? How can we share our knowledge with the rest? The answer is to make an API.

According to Wikipedia, An application programming interface (API) is an interface or communication protocol between a client and a server intended to simplify the building of client-side software. Sounds complex but this isn’t the case. In this tutorial, we will transform this algorithm that returns the most dominant colors of an image into an API.

Let’s see the code.

import PIL
from PIL import Image
import requests
from io import BytesIO
import webcolors
import pandas as pd

import webcolors
def closest_colour(requested_colour):
    min_colours = {}
    for key, name in webcolors. CSS3_HEX_TO_NAMES.items():
        r_c, g_c, b_c = webcolors.hex_to_rgb(key)
        rd = (r_c - requested_colour[0]) ** 2
        gd = (g_c - requested_colour[1]) ** 2
        bd = (b_c - requested_colour[2]) ** 2
        min_colours[(rd + gd + bd)] = name
    return min_colours[min(min_colours.keys())]

def top_colors(url, n=10):
    # read images from URL
    response = requests.get(url)
    img =

    # convert the image to rgb
    image = img.convert('RGB')
    # resize the image to 100 x 100
    image = image.resize((100,100))
    detected_colors =[]
    for x in range(image.width):
        for y in range(image.height):
    Series_Colors = pd.Series(detected_colors)

So what the “top color” function does is given a URL of an image it can return the top 10 dominant colors. Click here for more information.
We have to create a file with the code above in our working directory so we can import the function to our flask code.
Keep in mind that our function has to return a dictionary, that’s why we are transforming our Pandas Dataframe into a dictionary using the .to_dict() method.

Python Rest API Flask Script

So now we have our function, the next step is to create our Flask code. In our working directory we have to create a file with the following code:

from flask import Flask, jsonify, request


#we are importing our function from the file
from colors import top_colors

def index():
    if request.method=='GET':
#getting the url argument       
        url = request.args.get('url')
        return jsonify(result)
        return jsonify({'Error':"This is a GET API method"})

if __name__ == '__main__':,host='', port=9007)

At first, this might be confusing but it is not. We don’t have to analyze the whole script because using this as a base, we can create anything.
Firstly we have to import our function top_colors from our file. This is a GET method API so using the url = request.args.get(‘url’)
we are getting the value of the argument “url”.

Then, we are passing this value to our function and we are returning the result using the jsonify library to transform it into a JSON(that was the reason that our function had to return a dictionary instead of a Dataframe). The if statement is for those who will call the API as a POST method so it can return a warning. Finally, the port is up to you, here we are using 9007.

Having that, we can run the file to test it locally. The output will be something like this:

 * Serving Flask app "main" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 220-714-143
 * Running on (Press CTRL+C to quit)

Now we can go to a browser to test it. This API is running on localhost with port 9007 and it’s getting as argument a URL. So, for example, we can run the following using this image


It will return something like this:

burlywood: 0.1153,
cornsilk: 0.0252,
darksalmon: 0.2294,
darkslategray: 0.1046,
indianred: 0.1695,
lemonchiffon: 0.0207,
lightsalmon: 0.0499,
navajowhite: 0.0406,
rosybrown: 0.0929,
wheat: 0.0246

So finally we are alive! Now others can “drink” our knowledge using our flask rest API.

python rest api example

The next step is to deploy it on a server. We will show you how to do easily it in our future posts.

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

3 thoughts on “Python Rest API Example”

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

deploy a flask api

How to Process Requests in Flask

The most common payload of incoming data are the query strings, the form data and the JSON objects. Let’s provide