Functional Python Programming

(Wang) #1

A Functional Approach to Web Services


Injecting a state via cookies


The addition of cookies changes the overall relationship between a client and server
to become stateful. Interestingly, it involves no change to the HTTP protocol itself.
The state information is communicated via headers on the request and the reply. The
user agent will send cookies in request headers that match the host and path. The
server will send cookies to the user agent in response headers.


The user agent or browser must, therefore, retain a cache of cookie values and
include appropriate cookies in each request. The web server must accept cookies in
the request header and send cookies in the response header. The web server doesn't
need to cache cookies. A server merely uses cookies as additional arguments in a
request and additional details in a response.


While a cookie can, in principle, contain almost anything, the use of cookies has
rapidly evolved to contain just an identifier for a session state object. The server can
then use the cookie information to locate session state in some kind of persistent
storage. This means the server can also update the session state based on user agent
requests. It also means the server can discard sessions which are old.


The concept of a "session" exists outside the HTTP protocol. It is commonly defined
as a series of requests with the same session cookie. When an initial request is made,
no cookie is available, and a new session is created. Every subsequent request would
include the cookie. The cookie would identify the session state object on the server;
this object would have the information required by the server to provide consistent
web content gracefully.


The REST approach to web services, however, does not rely on cookies. Each REST
request is distinct and does not fit into an overall session framework. This makes
it less "user-friendly" than an interactive site that uses cookies to simplify a user's
interactions.


This also means that each individual REST request is, in principle, separately
authenticated. In many cases, a simple token is generated by the server to avoid the
client sending more complex credentials with every request. This leads to having the
REST traffic secured using Secured Socket Layer (SSL) protocols; the https scheme
is then used instead of http. We'll call both schemes HTTP throughout this chapter.


Considering a server with a functional design


One core idea behind HTTP is that the daemon's response is a function of the
request. Conceptually, a web service should have a top-level implementation that
can be summarized as follows:


response = httpd(request)

Free download pdf