Lecture 35

Making simple APIs with Flask

MCS 260 Fall 2021
David Dumas

Reminders

  • Homework 12 due Tue Nov 16 at 10am
  • Read the project 4 description
  • Project 4 proposals due by Nov 17

Flask

Flask is a Python web framework. It lets you build APIs and web sites with Python.

Competitors include:

  • Bottle — minimalist like Flask
  • Django — huge and full-featured

Installing Flask

Using pip to install, if the interpreter name is python3:


python3 -m pip install flask

Confirm installation by testing import in the REPL:


>>> import flask
>>>

If Flask is not installed, this will produce an error.

Decorators

Flask uses a lot of decorators, a Python feature we haven't covered yet.

Basically, on a line immediately before a function definition, you put a command beginning with @, e.g.


@decname
def f(x,y,z):

Here, decname needs to be replaced with the name of a decorator, which is a certain kind of higher-order function. It modifies the behavior of f.

Why decorators in Flask?

We might write a function that returns a string:

Why decorators in Flask?

We might write a function that returns a string:

Why decorators in Flask?

A Flask decorator lets us link it directly to a URL:

Why decorators in Flask?

A Flask decorator lets us link it directly to a URL:

Goal 1

Build API so that

/

returns

"Hello World".

Goal 2

Build API so that

/element/random

returns a JSON object with info about a randomly-selected chemical element.

Goal 3

Build API that checks whether a given word is a palindrome, so

/palindrome/test?word=banana

would return False in JSON.

Summary

  • Name localhost or IP address 127.0.0.1 is used to refer to the same host you're making a request from.
  • http://domain.com:1234/rest/of/URL/ means to use port 1234 instead of the default (which is 80 for HTTP).
  • If app is a flask.Flask object, the decorator @app.route("/path/part/of/URL/") makes a function into a URL handler.
  • Names of functions that handle URLs are distinct from the URLs they answer to.
  • flask.jsonify converts a Python value into a suitable return value from a URL handler.

References

Revision history

  • 2021-11-11 Initial publication