CS 257: Software Design

Lab: getting started with Flask

Nothing to hand in

Flask: a web framework

Once you have designed an HTTP-based API, you'll want to write code to implement it, and deploy that code on a publicly accessible server.

One of the biggest hassles of API implementation is the parsing of the URL. For example, if you're writing a server that expects to receive requests like "http://wherever.com/author/27", your server will need code to recognize that the caller is requesting the "author" resource with ID number 27. Once your server extracts this information, it will probably want to call a function get_author (or some similar name) with the parameter author_id=27. The get_author function will then query your database, assemble a JSON response, and send that response back to the client that made the original request.

In addition to URL parsing, there are other routine and tedious tasks involved in implementing web services. As a result, many people have developed web frameworks—tools to simplify some of these routine tasks. We will be using one such framework called Flask, one of the most popular Python web frameworks.

For now, you'll install Flask on your working computer, but eventually, you'll be deploying your web application on perlman.mathcs.carleton.edu, where Flask is already installed.

Installing Flask

There's all sorts of discussion of details on the official Flask installation page. That said, I don't recommend following all those instructions. The Flask people really love using virtual environments, for which there are many good arguments. But in my experience, both for myself and most of my CS257 students, virtual environments add more complexity to my setup without providing discernable benefits.

So, here's what I recommend you do.

Trying out a simple Flask application

So where are we?

There's nothing more to do for this lab, but here's a little discussion of what comes next.

At this point, you can launch a simple Flask web app on your working computer and access it via a browser, but only from a browser that is also running on your computer. We'll eventually move our Flask apps onto perlman.mathcs.carleton.edu so they can be accessed from elsewhere. But for now, you're set to start developing your own API.

To do that, you'll use the functions in flask_sample.py to give you an idea of how to build additional "@app.route" endpoints corresponding to the endpoints of the API you're trying to implement. You might also find the official Flask documentation helpful.

Here's one approach, pretending we're working on a books/authors API:

Alternatively, you could create all the endpoint stubs at once, test that they are getting called at the appropriate times, and then start implementing them one at a time.