Extending Flask REST API with WebSockets Extending Flask REST API with WebSockets flask flask

Extending Flask REST API with WebSockets


I have a working solution where I create "Rooms" for each property, but this requires two separate servers and duplication of endpoints.

The Socket.IO server and your HTTP server do not necessarily need to be separate, In all supported configurations you can host HTTP and Socket.IO applications with a single server.

I also don't see the endpoint duplication, but maybe this is because you think of Socket.IO event handlers as endpoints, while in fact they are not. With Socket.IO there is a single endpoint in the HTTP sense, since all Socket.IO traffic travels on a single URL. Your event handlers are just that, functions that are invoked when certain events pop up on the Socket.IO endpoint.

where the client connects to the same endpoint used in the REST API, but with the WebSocket protocol instead of joining rooms etc.

So you want your client to establish a separate WebSocket connection for each thing it wants to watch? That seems a bit resource intensive and not very scalable to me. If the client needs to watch 100 things, then it will have to maintain 100 WebSocket connections. Keep in mind that most browsers cap the number of WebSocket connections they can have open at a time, both per page and globally.

Socket.IO is a higher-level protocol that is built on top of WebSocket and HTTP. If you still prefer to use WebSocket directly, then you can take any of the available open source WebSocket servers and implement your application with that instead of Socket.IO. Here are a few options for Python off the top of my mind:

You are going to lose a few things that Socket.IO offers that are very handy:

  • Automatic reconnections
  • Automatic support for non-WebSocket clients via long-polling
  • Event-based dispatching
  • Rooms

So you need to make sure these are not important features, or you are okay implementing them yourself directly on the WebSocket server.