Using Flask to Build a Simple API

My journey getting to know Flask

Samantha Jackson
May 23 · 6 min read
Photo by on

Recently, I have been working with data and creating models that can predict…whatever I train them to predict! I used a dataset from an animal shelter to create a model that will predict the outcomes of animals at the shelter, based on their intake details (breed, color, size, location, etc.)

Creating and tuning these models is fascinating, but hopefully one day someone will want to use the models I have built in an automated fashion. Ideally, this will not involve them having to open my Jupyter notebook and run all the cells to obtain a prediction. To avoid this, I need to set up an API that will accept an input (more specifically, features) and spit out a prediction based on the model I have trained.

Hello Flask

According to its , Flask is “a microframework for Python based on Werkzeug, Jinja 2 and good intentions.”

In other words, Flask helps with building production-ready applications with Python. I found Flask particularly appealing due to the low barrier to entry — they make getting started extremely easy!

This is straight from their landing page

Within seconds of arriving to their web page, you can have a basic app up and running. Simply copy the python code you see and save as ‘hello.py’, pip install flask from your terminal, and run your ‘hello’ flask app!

With just a few lines of code, Flask has helped me launch a simple built in API server. It’s so easy!

Getting Up and Running

Now I’m a Flask pro (joke!), I can apply the basic format of the “hello” app to the app I originally set out to create. Starting small before tackling a model, I decided to see if I could add functionality to my ‘hello.py’ file by returning “Hello, {name}!”.

A quick search through the Flask documentation revealed a simple solution. I just had to import request and add name = request.args.get('name') to my ‘hello.py’ file. It worked!

By adding the request code, I was able to put a parameter (name) into the URL, and the API would return a customized greeting. It looked like this:

An exciting start, but not exactly what I was going for

This was cool, but not exactly what I was going for. Adding numerous parameters into a URL seemed tedious— I needed to find a better way.

A quick note from a beginner

Now is a good time to note that every time I changed my .py file, I had to close the flask instance that was running (ctrl+c in my terminal), and rerun $ flask run before refreshing my browser. This was a little painful, until I discovered that running $flask run —-reload tells flask to auto reload your code upon saving your python file.

Leveling up

Again, to get additional functionality, I needed to make only minor changes to my python file. However, to fully understand the changes I was making I needed know more about the basic functionality of an API server. As I understand it, Flask facilitates the communication between the python script I wrote (which will serve as the API server) and any incoming requests from a client (i.e. a Web browser). According to , a client needs four things for a valid request: URL, method, list of headers, and body. I’ll focus below on the first two, since I need to configure my API to be able to handle these. Luckily, Flask makes it easy.

If you compare this piece of code to the last, you can see the decorator has changed. By simply adding this decorator, I have configured a URL where the client can interact with the API and I have told Flask where it can direct the two different kinds of requests that my API will accept. A ['GET'] request from a client asks the server to retrieve a resource— in this case, it will retrieve the HTML that I have added (which can be rendered by a web browser as submission form with a submit button). A ['POST'] request asks the server to create a resource (i.e. use the input to return an output).

After setting up this API server, accessing it from my web browser looks like this:

Entry Form — User can type in their name, then click ‘Submit’
Output after clicking ‘Submit’!

Really cool! It’s time to see if I can get this working for a model.

Pickles

Not this kind of pickle. Photo by on

One important step for getting my model to predict over an API was pickling. I pickled my LabelEncoder, PolynomialFeatures, and my model itself. Basically, anything that was fit to my data at any point was pickled. This allowed me to call these models quickly in a new python file, without needing to retrain a model every time the API server starts.

By pickling my LabelEncoder and my PolynomialFeatures, it can accept strings as inputs, and only needs the basic features. Since both were already fit to my data, I simply call .transform() on the input features for each, just as I would have done after I trained them in my Jupyter notebook.

As for my model, once the pickled model is loaded, I just call .predict() on my encoded features and it will return a prediction.

Animal shelter outcome predictions

The code below shows how I set up an API server to produce a prediction based on animal features. As you can see, it has the same basic features as my ‘hello.py’ file — the decorators tell Flask the URL where it can be accessed, the types of requests it will accept, and how to respond to those requests. The only difference is that I created a render template to hold the HTML (because the HTML was long and ugly).

Checkout those pickles!

The API responding to my web browser looks like this:

Conclusion

Flask is really easy to get started with and has great documentation. It also provides templates to make your app creation as painless as possible. I have barely scratched the surface of Flask and its uses, but I’m already capable of turning these useful models I am building into something usable outside the Python environment.

All code is available on my

Better Programming

Advice for programmers.

Samantha Jackson

Written by

Data Science Student // Flatiron School

Better Programming

Advice for programmers.