Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing API via WebSockets using Python

Hobby coder here working on a weekend project.

I wish to access a publicly available API as present here: https://api.coinsecure.in/ It provides us with BitCoin trade data - the API is via websockets which i am not familiar with.

The Websocket URI is wss://coinsecure.in/websocket And the method i wished to test is : {"method": "recentbuytrades"}

I am able to access the WebScocket API using the "websocket-client" in Python as listed here: https://pypi.python.org/pypi/websocket-client/

But unfortunately I am unable to figure out how to retrieve the data for the particular method - {"method": "recentbuytrades"}

Would be very grateful for any guidance that you could provide on extracting the data for this particular method.

Best, Ryan

[EDIT] Current code I am using is this:

from websocket import create_connection
ws = create_connection("wss://coinsecure.in/websocket")
result =  ws.recv()
print ("Received '%s'" % result)
ws.close()
like image 460
ryan c788 Avatar asked Jan 30 '16 18:01

ryan c788


People also ask

How does Python communicate with WebSockets?

WebSocket Client with PythonCreate a new File “client.py” and import the packages as we did in our server code. Now let's create a Python asynchronous function (also called coroutine). async def test(): We will use the connect function from the WebSockets module to build a WebSocket client connection.

Can I use WebSockets FOR REST API?

Yes. You can use REST over WebSocket with library like SwaggerSocket.

What is WebSocket API in Python?

websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio, Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API. Documentation is available on Read the Docs.


1 Answers

Try this:

from websocket import create_connection
ws = create_connection("wss://coinsecure.in/websocket")
ws.send('{"method": "recentbuytrades"}')

while True:
  result =  ws.recv()
  print ("Received '%s'" % result)

ws.close()

Note the ws.send() method, which tells the API what you want. Next, the while True infinite loop - WebSockets are indefinite connections; information is often sent over them more than once. You'll get a bunch of information (a 'frame') here from the server (looks like JSON), handle it, and then wait for the next bunch to come.

It also looks like the API will send you data you don't necessarily want. You may want to throw the frame out if it doesn't contain the recentbuytrades key.

like image 74
Undo Avatar answered Oct 25 '22 10:10

Undo