r/FastAPI • • Jul 06 '21

Question How to send data through a web socket from an HTTP request?

I want to send data to a user through a web socket when some action is performed in an HTTP endpoint. Is there a mechanism to do that with the fast API WebSocket? I had done this earlier with flask and socket-io. I have been looking for implementing this in fast API.

Thanks

1 Upvotes

4 comments sorted by

4

u/[deleted] Jul 06 '21

It's literally in the documentation.

https://fastapi.tiangolo.com/advanced/websockets/

5

u/Nick0tin Jul 06 '21

Since the documentation doesn't exactly include what OP is asking, I will add that creating a manager for all websockets connections, as shown in docs above, you can use the manager to send message to any websocket in your http endpoint as you wish, just import the manager

1

u/[deleted] Jul 06 '21

if it's unidirectional data transfer then you could go for server sent events by using an event source. from your use case it sounds like its unidirectional.

1

u/Sigfurd2345 Jul 07 '21

Yes, there's a mechanism to do what you want.

I'm currently using python-socketio for the sockets.

It works great for an asynchronous server. I'm seeing better performance than when I'm using flask & flask-socketio.