3

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

3 Answers 3

12

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Note that in recent versions the argument is called additional_headers.
3

In more recent versions the library's api changed and now they use the argument additional_headers to add new headers:

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

Reference: https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html#opening-a-connection

Comments

-3

First create a websocket using websockets.connect.
Then send the JSON header in websocket.send(header)
And then start processing the responses.

This should work:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.