rest – HTTPSession for session state in web APIs?


When people talk about a “stateless API”, they don’t mean that requests can’t have any effect on the state of the server – the “S” in “REST” stands for “state”, after all – but that the meaning of a request doesn’t change based on state. This is achieved by making each stateful object an explicit part of the API.

So, a stateful API might have a verb “add item to my shopping basket”, with a meaning entirely dependent on matching the request to a previous “create basket” request. In a stateless API, you might instead say “add item to basket 42”, with the identifier “42” having been remembered by the client from the “create basket” response.

REST takes this further, and says that the objects should be the central concept, rather than actions with side-effects on those objects. So GET /basket/42 might return the current contents of that basket, POST /basket/42/items might add a product to it, and DELETE /basket/42/items/13 remove a product.

The reason this is useful is that it gives the client more flexibility in how to use the API, and the API more flexibility in the features it offers. For instance, a client might want to maintain two separate baskets, but based on one set of search results; or the API might offer the ability to clone a basket, or merge two baskets to pay for them at once.

So rather than moving further towards using a transparent “session” handled by the server software, I suggest you start thinking about what stateful objects each service’s session identifier represents.

Even if you don’t redesign the services to make those objects explicit, you can reframe your architectural decisions:

  • What is the appropriate lifetime for this object?
  • How often is this object read vs written?
  • What would be the consequences if this object was lost due to a server failure?
  • Do you need central observability of this object?

All of these need asking anyway if you use HTTPSession, since you need to configure where it stores its data, how long it stores it for, and so on. The main thing that would automate is the least relevant for an API: how to make a stateless web browser act like a stateful client without custom client code.