I always use REST API when I get or post some data. But WebSocket can also do that.
So, I am confused about the difference between WebSocket and REST API when I try to get or post some data.
WebSocket is a stateful protocol, whereas REST is based on stateless protocol, i.e. the client does not need to know about the server and the same hold true for the server. WebSocket connection can scale vertically on a single server, whereas REST, which is HTTP based, can scale horizontally.
REST is the most commonly used architecture for developing APIs in recent years. It supports a half-duplex data transmission between the client and server. In the case of full-duplex data transmission, WebSockets are used.
Fast Reaction TimeWebSockets allow for a higher amount of efficiency compared to REST because they do not require the HTTP request/response overhead for each message sent and received.
The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.
A REST API uses HTTP as the underlying protocol for communication, which in turn follows the request and response paradigm. However, with WebSockets, although the communication still starts off over HTTP, it is further elevated to follow the WebSockets protocol if both the server and the client are compliant with the protocol (not all entities support the WebSockets protocol).
Now with WebSockets, it is possible to establish a full duplex and persistent connection between the client and a server. This means that unlike a request and a response, the connection stays open for as long as the application is running, and since it is full duplex, two way simultaneous communication is possible i.e now the server is capable of initiating a communication and 'push' some data to the client.
This is the primary concept use in the realtime technology where you are able to get new updates in the form of server push without the client having to request (refresh the page) repeatedly. Examples of such applications are Uber car's location tracking, Push Notifications, Stock market prices updating in realtime etc.
Here's a video from a presentation I gave earlier this month about websockets and how they are different than using the regular REST APIs: https://www.youtube.com/watch?v=PJZ06MLXGwA&list=PLZWI9MjJG-V_Y52VWLPZE1KtUTykyGTpJ&index=2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With