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 create 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.

The output of our API, cannot be a Pandas Dataframe. So we will convert it into JSON. An easy way to do this is to return the Dataframe as a dictionary and then in our flask code, using the Jsonify function of flask we can convert it into JSON. That’s why we are using the .to_dict() method in the top_colors function.

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)

You don’t have to understand the whole script, just use it as a base for your API projects.

Firstly we have to import our function top_colors from the file. Using the url = request.args.get(‘url’) we are getting the value of the argument “url” which in our case is the URL of an image.

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 as we said above.

The if statement is for those who will call the API as a POST method so it can return a warning. Lastly, the port is up to you, we are using the 9007.

Finally, we can run the file to test it locally. Just run the following in your terminal:


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)

That means that our API is running on localhost using the 9007 port.

Now we can go to a browser to test it. To add our variable(image URL) in the API’s URL, we have to add it at the end like follows ?variable=. In our example our API’s URL is the following:

http://localhost:9007/?url=[[url of an image]].

So, for example, Let’s say we want to get the dominant colors of the following image from Unsplash:

We have to hit the following URL in our browser:


Then, we will get the following output:

{'black': 0.2843,
'gainsboro': 0.2812,
'darkslategray': 0.1889,
'lavender': 0.0668,
'lightsteelblue': 0.0448,
'lightgray': 0.0405,
'darkgray': 0.0189,
'darkolivegreen': 0.0172,
'dimgray': 0.0144,
'lightslategray': 0.0129}

Success, we got the dominant colors of that image!

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


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s