Sending and receiving messages over WebSockets
WebSocket connections enable bidirectional communication between clients and servers, allowing the real-time exchange of messages. This recipe will bring us one step closer to creating our chat application by showing how to enable the FastAPI application to receive messages over WebSockets and print them to the terminal output.
Getting ready
Before starting the recipe, make sure you know how to set up a WebSocket connection in FastAPI, as explained in the previous recipe. Also, you will need a tool to test WebSockets, such as Postman, on your machine.
How to do it…
We will enable our chatroom endpoint to receive messages from the client to print them to the standard output.
Let’s start by defining the logger. We will use the logger from the uvicorn
package (as we did in other recipes – see, for example, Creating custom middlewares in Chapter 8, Advanced Features and Best Practices), which is the one...