Is it possible to call http API by websocket?

Issue

I was asked me to make an api call using websocket with php Ratchet at work. Since I’m totally unfamilier with websocket so I googled and watched youtube videos to solve this problem, but The more I searched, the more I felt it is impossible to call api with websocket.

Am I missing something or is it really impossible to call api by websocket?
If it is possible, can you please show me an example how to do it

I know i might sound awkward since I don’t have a solid understanding of websockets, English isn’t even my first language, but i’m really desperate please help me

Solution

A REST API is fundamentally different from a WebSocket API.

REST API

Calls are made through HTTP(S). You can use AJAX (see here: https://en.wikipedia.org/wiki/Ajax_(programming)) to access HTTP endpoints directly from the browser. In JavaScript you would use the Fetch-API (see here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make calls. Each and every call is stateless per definition. Cookies and special headers must be send with every request to create a context (e.g. user that is logged in).

Example (Client):

fetch('http://example.com/my-rest-api/endpoint1')
  .then(response => response.json())
  .then(data => console.log(data));

Example (Server):

app.get('/my-rest-api/endpoint1', handlerFunc);

WebSocket API

A stateful connection must be established between a client and a server. The client and server can exchange messages via the connection. Unlike a REST-API messages can be send bidirectional.
A high-level implementation of the WebSocket API is Socket.io.
An API can be designed by defining message types with payloads.
I also would not recommend to use PHP for a WS-API (even though there is a solution like Ratchet). Use a language/runtime that was developed for event-based use cases like this (e.g. nodeJS).

Example (Client):

const socket = SocketClass('example.com/my-websocket-api');

// variant 1 with callbacks
const response = socket.sendMessage('endpoint1', myData);

// variant 2 with message listener
socket.on('endpoint1Response', handlerFunc);
socket.sendMessage('endpoint1', myData);

Example (Server):

const serverSocket = SocketClass('/my-websocket-api');
serverSocket.on('connection', function (socket) {

    // variant 1 with callbacks
    socket.on('endpoint1', (data, callback) => {
        callback(null, responseData);
    });

    // variant 2 with message listener
    socket.on('endpoint1', (data, cb) => {
        socket.emit('endpoint1Answer', responseData);
    });
});

Answered By – adroste

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published