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 = Image.open(BytesIO(response.content)) # 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): detected_colors.append(closest_colour(image.getpixel((x,y)))) Series_Colors = pd.Series(detected_colors) output=Series_Colors.value_counts()/len(Series_Colors) return(output.head(n).to_dict())
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 colors.py 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 main.py file with the following code:
from flask import Flask, jsonify, request app=Flask(__name__) #we are importing our function from the colors.py file from colors import top_colors @app.route("/",methods=['GET','POST']) def index(): if request.method=='GET': #getting the url argument url = request.args.get('url') result=top_colors(str(url)) return jsonify(result) else: return jsonify({'Error':"This is a GET API method"}) if __name__ == '__main__': app.run(debug=True,host='0.0.0.0', 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 colors.py 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 main.py 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 http://0.0.0.0:9007/ (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 https://image.shutterstock.com/z/stock-photo-at-o-clock-at-the-top-of-the-mountains-sunrise-1602307492.jpg:
http://localhost:9007/?url=https://image.shutterstock.com/z/stock-photo-at-o-clock-at-the-top-of-the-mountains-sunrise-1602307492.jpg:
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.

The next step is to deploy it on a server. We will show you how to do easily it in our future posts.
3 thoughts on “Python Rest API Example”
Looking forward to the “go live” tutorial!
Very nice content!
Stay Tuned!