Functional Python Programming

(Wang) #1
Chapter 15

Defining web services as functions


We'll look at a RESTful web service, which can "slice and dice" a source of data
and provide downloads as JSON, XML, or CSV files. We'll provide an overall
WSGI-compatible wrapper but the functions which do the "real work" of the
application won't be narrowly constrained to fit the WSGI.


We'll use a simple dataset with four subcollections: the Anscombe Quartet. We
looked at ways to read and parse this data in Chapter 3, Functions, Iterators, and
Generators". It's a small set of data but it can be used to show the principles of a
RESTful web service.


We'll split our application into two tiers: a web tier, which will be a simple WSGI
application, and the rest of the processing, which will be more typical functional
programming. We'll look at the web tier first so that we can focus on a functional
approach to provide meaningful results.


We need to provide two pieces of information to the web service:



  • The quartet that we want—this is a "slice and dice" operation. For this
    example, it's mostly just a "slice".

  • The output format we want.


The data selection is commonly done via the request path. We can request "/
anscombe/I/" or "/anscombe/II/" to pick specific datasets from the quartet.
The idea is that a URL defines a resource, and there's no good reason for the
URL to ever change. In this case, the dataset selectors aren't dependent on dates,
or some organizational approval status or other external factors. The URL is timeless
and absolute.


The output format is not a first class part of the URL. It's just a serialization
format—not the data itself. In some cases, the format is requested via the HTTP
Accept header. This is hard to use from a browser but easy to use from an
application using a RESTful API. When extracting data from the browser, a query
string is commonly used to specify the output format. We'll use the "?form=json"
method at the end of the path to specify the JSON output format.


A URL we can use will look like this:


http://localhost:8080/anscombe/III/?form=csv


This would request a CSV download of the third dataset.

Free download pdf