How do I create a websocket connection in Python?

Question:

I am trying to create a websocket connection with following code (just to make a test connection):

async def webSocket():

async with websockets.connect("wss://push1-v2.kucoin.com") as test:
    await test.send("/api/v1/bullet-public")
    result = await test.recv()
    print(result)

if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(webSocket())

The result is supposed to be a json response like this:

{
"code": "200000",
"data": {

    "instanceServers": [
        {
            "endpoint": "wss://push1-v2.kucoin.com/endpoint",
            "protocol": "websocket",
            "encrypt": true,
            "pingInterval": 50000,
            "pingTimeout": 10000
        }
    ],
    "token": "vYNlCtbz4XNJ1QncwWilJnBtmmfe4geLQDUA62kKJsDChc6I4bRDQc73JfIrlFaVYIAE0Gv2--MROnLAgjVsWkcDq_MuG7qV7EktfCEIphiqnlfpQn4Ybg==.IoORVxR2LmKV7_maOR9xOg=="
}

}

Instead when I execute the code I get following error:

for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

Is there maybe a setting I would have to change to my python set up? I use version 3.9.

Asked By: Aboji

||

Answers:

The target for that first POST (/api/v1/bullet-public) is the API HTTPS which is https://api.kucoin.com/

You can manually try it by using your command line or terminal:

curl -i -X POST https://api.kucoin.com/api/v1/bullet-public
Answered By: Víctor Díaz

I was able to get a successfull response using requests.

import requests


params = {"code": 200000}
r = requests.post(url=url, data=params)
print(r.text)

Output:

{"code":"200000","data":{"token":"2neAiuYvAU61ZDXANAGAsiL4-iAExhsBXZxftpOeh_55i3Ysy2q2LEsEWU64mdzUOPusi34M_wGoSf7iNyEWJ8rOsUMiCDkA8T3XpfNKOQvf0ImYa78XstiYB9J6i9GjsxUuhPw3BlrzazF6ghq4L7-hL6el-nEq88XUTYg8sSU=rdcepcTiY0DA==","instanceServers":[{"endpoint":"wss://ws-api.kucoin.com/endpoint","encrypt":true,"protocol":"websocket","pingInterval":18000,"pingTimeout":10000}]}}

My main mistake was using requests.get instead of requests.post as specified in the Kucoin API docs. – https://docs.kucoin.com/#apply-connect-token

Answered By: Randy