Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send headers in Websockets connection request from Python client

What is the correct method / syntax for adding headers to a websocket connection request using Python Websockets ?

The server I'm trying to connect to requires headers in the connection request for authentication

async def connect():
    async with websockets.connect("wss://site.com/ws") as websocket:
        response = await websocket.recv()
        print(response)

    # eg. does not work:
    async with websockets.connect(f"wss://site.com/ws, header={headers}") as websocket:
    async with websockets.connect(f"wss://site.com/ws, extra_headers:{headers}") as websocket:

Similar question was asked here but did not answer the core of the question: How to send 'Headers' in websocket python

like image 575
leo_cape Avatar asked Jan 27 '26 01:01

leo_cape


1 Answers

According to documentation, you can pass headers in additional_headers param of connect() function. Details here.

So code should look something like this:

async def connect():
    async with websockets.connect("wss://site.com/ws", additional_headers=headers) as websocket:
        response = await websocket.recv()
        print(response)
like image 134
impenetrabl1 Avatar answered Jan 28 '26 15:01

impenetrabl1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!