Defining WebSockets for Two-Way Interactive Communication in FastAPI
HTTP is a simple yet powerful technique for sending data to and receiving data from a server. As we’ve seen, the principles of request and response are at the core of this protocol: when developing our API, our goal is to process the incoming request and build a response for the client. Thus, in order to get data from the server, the client always has to initiate a request first. In some contexts, however, this may not be very convenient. Imagine a typical chat application: when a user receives a new message, we would like them to be notified immediately by the server. Working only with HTTP, we would have to make requests every second to check whether new messages had arrived, which would be a massive waste of resources. This is why a new protocol has emerged: WebSocket. The goal of this protocol is to open a communication channel between a client and a server so that they can exchange data in real time, in...