How to combine websockets and http to create a REST API that keeps data up to date?

David Berg picture David Berg · Oct 29, 2015 · Viewed 13.6k times · Source

I am thinking about buildning a REST API with both websockets and http where I use websockets to tell the client that new data is available or provide the new data to the client directly.

Here are some different ideas of how it could work:
ws = websocket

Idea A:

  1. David get all users with GET /users
  2. Jacob add a user with POST /users
  3. A ws message is sent to all clients with info that a new user exist
  4. David recive a message by ws and calls GET /users

Idea B:

  1. David get all users with GET /users
  2. David register to get ws updates when a change is done to /users
  3. Jacob add a user with POST /users
  4. The new user is sent to David by ws

Idea C:

  1. David get all users with GET /users
  2. David register to get ws updates when a change is done to /users
  3. Jacob add a user with POST /users and it gets the id 4
  4. David receive the id 4 of the new user by ws
  5. David get the new user with GET /users/4

Idea D:

  1. David get all users with GET /users
  2. David register to get ws updates when changes is done to /users.
  3. Jacob add a user with POST /users
  4. David receive a ws message that changes is done to /users
  5. David get only the delta by calling GET /users?lastcall='time of step one'

Which alternative is the best and what are the pros and cons?
Is it another better 'Idea E'?
Do we even need to use REST or is ws enought for all data?

Edit
To solve problems with data getting out of sync we could provide the header
"If-Unmodified-Since"
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Unmodified-Since
or "E-Tag"
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
or both with PUT requests.


Answer

vtortola picture vtortola · Oct 29, 2015

Idea B is for me the best, because the client specifically subscribes for changes in a resource, and gets the incremental updates from that moment.

Do we even need to use REST or is ws enought for all data?

Please check: WebSocket/REST: Client connections?