Setting Up a Simple API

Setting Up a Simple APIMy Journey Getting to Know FlaskSamantha JacksonBlockedUnblockFollowFollowingMay 23Lately, I’ve been working with interesting data and creating really cool models that can predict … whatever I train them to predict.

Most recently, I worked with 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.

)While I think creating and tuning these models is fascinating, I realize that one day someone will need to use the models I build in some automated fashion.

And I imagine that this fashion will not include opening my jupyter notebook and running all of the cells to ultimately obtain a prediction.

For this reason, I wanted to try setting up an API that can accept an input (more specifically, features) and spit out a prediction based on the model I’ve trained.

Hello FlaskAccording to its landing page, Flask is “a microframework for Python based on Werkzeug, Jinja 2 and good intentions.

”http://flask.

pocoo.

org/In other words, Flask helps with building production-ready applications with Python.

I found Flask particularly appealing due to the super low barrier to entry.

They make getting started extremely easy!This is straight from their landing pageWithin 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 very simple builtin API server.

So easy!Getting Up and RunningNow that I’m a Flask pro (ha!), I can apply the basic format of the “hello” app to the app that I originally set out to create.

I have to admit that I started small for this project.

I decided to see if I could add functionality to my ‘hello.

py’ file, like returning “Hello, {name}!”, before tackling a model.

Some quick searching through the Flask documentation resulted in a simple solution.

I just had to import request and add name = request.

args.

get('name') to my ‘hello.

py’ file.

This 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 forThis was cool, but not exactly what I was going for.

Adding numerous parameters into a URL seemed tedious, so I needed to find a better way.

A Quick Note from a BeginnerI feel like now is a good time to note that each time I changed my .

py file, I needed 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 UpAgain, to get additional functionality, I needed to make only minor changes to my python file.

However, understanding my changes required I get a better understanding of 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 Gonzalo Vázquez, a client needs four things for a valid request: URL, method, list of headers, 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 this easy for us.

If you take a closer look at this code compared to the last, you can see the decorator changed a bit.

By simply adding this decorator, I’ve configured a URL where the client can interact with the API and I’ve 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 some resource.

In this case, it’ll retrieve the HTML that I’ve added (which can be rendered by a web browser into a submission form with a submit button!).

A ['POST'] request asks the server to create a resource (i.

e.

use the input to return some 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.

Time to see if I can get this working for a model.

PicklesOne very 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, I’m able to accept strings as inputs, and only need the basic features.

Since both were already fit to my data, I can 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 simply need to call .

predict() on my encoded features and my model will return a prediction.

Animal Shelter Outcome PredictionsBelow shows how I set up an API server to produce a prediction based on animal features.

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 here is I created a render template to hold the HTML (because the HTML was long and ugly).

The final code looked like this:Checkout those pickles!And the API responding to my web browser looks like this:ConclusionFlask is super easy to get started with and has great documentation.

They also provide templates to make your app creation as painless as they can.

I realize I’ve barely scratched the surface of Flask and its uses, but at least now I’m capable of turning these really cool models that I’m building into something useable outside of Python.

All code is available on my Github.

. More details

Leave a Reply