Using FastAPI for socket chat system?

Viewed 817

How would one implement a comprehensive chat system using sockets within FastAPI. Specifically keeping the following in mind:

  • Multiple Chat rooms many-to-many between users
  • Storing messages with a SQL or NoSQL database for persistence
  • Security: Authentication or possibly encryption

I've looked at some libraries, but actual useful implementations are far between, regrettably.

Any advice or redirects towards places for more information will be of great help!

1 Answers
  1. For chat rooms you could use FastAPI builtin websockets support and add redis pubsub or PostgreSQL pg_notify to it for sending messages to all participants in the room.
  2. Storing messages in PostgreSQL is a solid choice because of its long history and stability.
  3. Authentication can be handled by OAuth2 provider in FastAPI. Authorization can be handled by OAuth2 scopes that is hidden in the Advanced Security section in the FastAPI Documentation. Encryption is provided by HTTPS and reverse proxy that you put in front of your app.

There aren't any fully ready made libraries that provide everything out of the box. But breaking down the problem in to smaller pieces and then working on those will get you pretty far.

  1. Write down what fields/data you want to store about your users, chat rooms, messages.
  2. Implement those basic models in FastAPI probably using SQLAlchemy.
  3. Wire up those models to api endpoints so that you can use those models in Swagger (list chatrooms, get and post messages into chatrooms).
  4. Implement a websocket endpoint in FastAPI that will echo back everything sent to it. That should allow you to wire up some client side javascript for sending and receiving messages from the websocket.
  5. Modify your exising message storing endpoint to push the same message also to redis publish topic and change your websocket endpoint to subscribe to the redis subscribe topic.
  6. Add authentication to your endpoints. At first basic user/password, later more advanced configurations.
  7. Add reverse proxy with https in front and voila.
Related