Open In App

What is the use of WebSocket API ?

API stands for Application Programming Interface. API can be defined as a predefined set of instructions that describes how different applications can communicate with one another. So one can think of API as a middleman for transferring data between a web server and the application. Every app is using some kind of API to transfer data between applications. API provides the ability for different applications to open up their functionalities and data to other external parties to make use of it and develop new applications. Google Maps API and Twitter API are some well-known examples.

WebSocket: WebSocket is a communication protocol that is mainly used for communication between a client and server.



Features of WebSocket are:

WebSocket API: WebSocket API allows us to create web sockets, it is a javascript API that is capable of full-duplex communication using a TCP connection. WebSocket uses port 80 by default.



Features of WebSocket API are:

Use of WebSocket API: There is a wide range of uses of WebSocket API’s some of them are:

Websocket Implementation Using Python Fastapi:




from fastapi import FastAPI, WebSocket
 
app = FastAPI()
 
@app.websocket("/ws")
async def websocket_endpoint(webs: WebSocket):
      await webs.accept()
    while True:
      raw_text = await webs.receive_text()
      await webs.send_text(f'received data {raw_text}')
       
       
  # To test the code use, ws://localhost:8000/ws
  #in postman

Article Tags :