WebSockets

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

You can use WebSockets with FastAPI.

Install WebSockets

First you need to install WebSockets:

WebSockets - 图1

WebSockets client

In production

In your production system, you probably have a frontend created with a modern framework like React, Vue.js or Angular.

And to communicate using WebSockets with your backend you would probably use your frontend’s utilities.

Or you might have a native mobile application that communicates with your WebSocket backend directly, in native code.

Or you might have any other way to communicate with the WebSocket endpoint.


But for this example, we’ll use a very simple HTML document with some JavaScript, all inside a long string.

This, of course, is not optimal and you wouldn’t use it for production.

In production you would have one of the options above.

But it’s the simplest way to focus on the server-side of WebSockets and have a working example:

  1. from fastapi import FastAPI, WebSocket
  2. from fastapi.responses import HTMLResponse
  3. app = FastAPI()
  4. html = """
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <title>Chat</title>
  9. </head>
  10. <body>
  11. <h1>WebSocket Chat</h1>
  12. <form action="" onsubmit="sendMessage(event)">
  13. <input type="text" id="messageText" autocomplete="off"/>
  14. <button>Send</button>
  15. </form>
  16. <ul id='messages'>
  17. </ul>
  18. <script>
  19. var ws = new WebSocket("ws://localhost:8000/ws");
  20. ws.onmessage = function(event) {
  21. var messages = document.getElementById('messages')
  22. var message = document.createElement('li')
  23. var content = document.createTextNode(event.data)
  24. message.appendChild(content)
  25. messages.appendChild(message)
  26. };
  27. function sendMessage(event) {
  28. var input = document.getElementById("messageText")
  29. ws.send(input.value)
  30. input.value = ''
  31. event.preventDefault()
  32. }
  33. </script>
  34. </body>
  35. </html>
  36. """
  37. @app.get("/")
  38. async def get():
  39. return HTMLResponse(html)
  40. @app.websocket("/ws")
  41. async def websocket_endpoint(websocket: WebSocket):
  42. await websocket.accept()
  43. while True:
  44. data = await websocket.receive_text()
  45. await websocket.send_text(f"Message text was: {data}")

Create a websocket

In your FastAPI application, create a websocket:

  1. from fastapi import FastAPI, WebSocket
  2. from fastapi.responses import HTMLResponse
  3. app = FastAPI()
  4. html = """
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <title>Chat</title>
  9. </head>
  10. <body>
  11. <h1>WebSocket Chat</h1>
  12. <form action="" onsubmit="sendMessage(event)">
  13. <input type="text" id="messageText" autocomplete="off"/>
  14. <button>Send</button>
  15. </form>
  16. <ul id='messages'>
  17. </ul>
  18. <script>
  19. var ws = new WebSocket("ws://localhost:8000/ws");
  20. ws.onmessage = function(event) {
  21. var messages = document.getElementById('messages')
  22. var message = document.createElement('li')
  23. var content = document.createTextNode(event.data)
  24. message.appendChild(content)
  25. messages.appendChild(message)
  26. };
  27. function sendMessage(event) {
  28. var input = document.getElementById("messageText")
  29. ws.send(input.value)
  30. input.value = ''
  31. event.preventDefault()
  32. }
  33. </script>
  34. </body>
  35. </html>
  36. """
  37. @app.get("/")
  38. async def get():
  39. return HTMLResponse(html)
  40. @app.websocket("/ws")
  41. async def websocket_endpoint(websocket: WebSocket):
  42. await websocket.accept()
  43. while True:
  44. data = await websocket.receive_text()
  45. await websocket.send_text(f"Message text was: {data}")

Technical Details

You could also use from starlette.websockets import WebSocket.

FastAPI provides the same WebSocket directly just as a convenience for you, the developer. But it comes directly from Starlette.

Await for messages and send messages

In your WebSocket route you can await for messages and send messages.

  1. from fastapi import FastAPI, WebSocket
  2. from fastapi.responses import HTMLResponse
  3. app = FastAPI()
  4. html = """
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <title>Chat</title>
  9. </head>
  10. <body>
  11. <h1>WebSocket Chat</h1>
  12. <form action="" onsubmit="sendMessage(event)">
  13. <input type="text" id="messageText" autocomplete="off"/>
  14. <button>Send</button>
  15. </form>
  16. <ul id='messages'>
  17. </ul>
  18. <script>
  19. var ws = new WebSocket("ws://localhost:8000/ws");
  20. ws.onmessage = function(event) {
  21. var messages = document.getElementById('messages')
  22. var message = document.createElement('li')
  23. var content = document.createTextNode(event.data)
  24. message.appendChild(content)
  25. messages.appendChild(message)
  26. };
  27. function sendMessage(event) {
  28. var input = document.getElementById("messageText")
  29. ws.send(input.value)
  30. input.value = ''
  31. event.preventDefault()
  32. }
  33. </script>
  34. </body>
  35. </html>
  36. """
  37. @app.get("/")
  38. async def get():
  39. return HTMLResponse(html)
  40. @app.websocket("/ws")
  41. async def websocket_endpoint(websocket: WebSocket):
  42. await websocket.accept()
  43. while True:
  44. data = await websocket.receive_text()
  45. await websocket.send_text(f"Message text was: {data}")

You can receive and send binary, text, and JSON data.

Try it

If your file is named main.py, run your application with:

WebSockets - 图2

Open your browser at http://127.0.0.1:8000.

You will see a simple page like:

WebSockets - 图3

You can type messages in the input box, and send them:

WebSockets - 图4

And your FastAPI application with WebSockets will respond back:

WebSockets - 图5

You can send (and receive) many messages:

WebSockets - 图6

And all of them will use the same WebSocket connection.

Using Depends and others

In WebSocket endpoints you can import from fastapi and use:

  • Depends
  • Security
  • Cookie
  • Header
  • Path
  • Query

They work the same way as for other FastAPI endpoints/path operations:

Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.6+ non-Annotated

  1. from typing import Annotated
  2. from fastapi import (
  3. Cookie,
  4. Depends,
  5. FastAPI,
  6. Query,
  7. WebSocket,
  8. WebSocketException,
  9. status,
  10. )
  11. from fastapi.responses import HTMLResponse
  12. app = FastAPI()
  13. html = """
  14. <!DOCTYPE html>
  15. <html>
  16. <head>
  17. <title>Chat</title>
  18. </head>
  19. <body>
  20. <h1>WebSocket Chat</h1>
  21. <form action="" onsubmit="sendMessage(event)">
  22. <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
  23. <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
  24. <button onclick="connect(event)">Connect</button>
  25. <hr>
  26. <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
  27. <button>Send</button>
  28. </form>
  29. <ul id='messages'>
  30. </ul>
  31. <script>
  32. var ws = null;
  33. function connect(event) {
  34. var itemId = document.getElementById("itemId")
  35. var token = document.getElementById("token")
  36. ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
  37. ws.onmessage = function(event) {
  38. var messages = document.getElementById('messages')
  39. var message = document.createElement('li')
  40. var content = document.createTextNode(event.data)
  41. message.appendChild(content)
  42. messages.appendChild(message)
  43. };
  44. event.preventDefault()
  45. }
  46. function sendMessage(event) {
  47. var input = document.getElementById("messageText")
  48. ws.send(input.value)
  49. input.value = ''
  50. event.preventDefault()
  51. }
  52. </script>
  53. </body>
  54. </html>
  55. """
  56. @app.get("/")
  57. async def get():
  58. return HTMLResponse(html)
  59. async def get_cookie_or_token(
  60. websocket: WebSocket,
  61. session: Annotated[str | None, Cookie()] = None,
  62. token: Annotated[str | None, Query()] = None,
  63. ):
  64. if session is None and token is None:
  65. raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
  66. return session or token
  67. @app.websocket("/items/{item_id}/ws")
  68. async def websocket_endpoint(
  69. *,
  70. websocket: WebSocket,
  71. item_id: str,
  72. q: int | None = None,
  73. cookie_or_token: Annotated[str, Depends(get_cookie_or_token)],
  74. ):
  75. await websocket.accept()
  76. while True:
  77. data = await websocket.receive_text()
  78. await websocket.send_text(
  79. f"Session cookie or query token value is: {cookie_or_token}"
  80. )
  81. if q is not None:
  82. await websocket.send_text(f"Query parameter q is: {q}")
  83. await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
  1. from typing import Annotated, Union
  2. from fastapi import (
  3. Cookie,
  4. Depends,
  5. FastAPI,
  6. Query,
  7. WebSocket,
  8. WebSocketException,
  9. status,
  10. )
  11. from fastapi.responses import HTMLResponse
  12. app = FastAPI()
  13. html = """
  14. <!DOCTYPE html>
  15. <html>
  16. <head>
  17. <title>Chat</title>
  18. </head>
  19. <body>
  20. <h1>WebSocket Chat</h1>
  21. <form action="" onsubmit="sendMessage(event)">
  22. <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
  23. <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
  24. <button onclick="connect(event)">Connect</button>
  25. <hr>
  26. <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
  27. <button>Send</button>
  28. </form>
  29. <ul id='messages'>
  30. </ul>
  31. <script>
  32. var ws = null;
  33. function connect(event) {
  34. var itemId = document.getElementById("itemId")
  35. var token = document.getElementById("token")
  36. ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
  37. ws.onmessage = function(event) {
  38. var messages = document.getElementById('messages')
  39. var message = document.createElement('li')
  40. var content = document.createTextNode(event.data)
  41. message.appendChild(content)
  42. messages.appendChild(message)
  43. };
  44. event.preventDefault()
  45. }
  46. function sendMessage(event) {
  47. var input = document.getElementById("messageText")
  48. ws.send(input.value)
  49. input.value = ''
  50. event.preventDefault()
  51. }
  52. </script>
  53. </body>
  54. </html>
  55. """
  56. @app.get("/")
  57. async def get():
  58. return HTMLResponse(html)
  59. async def get_cookie_or_token(
  60. websocket: WebSocket,
  61. session: Annotated[Union[str, None], Cookie()] = None,
  62. token: Annotated[Union[str, None], Query()] = None,
  63. ):
  64. if session is None and token is None:
  65. raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
  66. return session or token
  67. @app.websocket("/items/{item_id}/ws")
  68. async def websocket_endpoint(
  69. *,
  70. websocket: WebSocket,
  71. item_id: str,
  72. q: Union[int, None] = None,
  73. cookie_or_token: Annotated[str, Depends(get_cookie_or_token)],
  74. ):
  75. await websocket.accept()
  76. while True:
  77. data = await websocket.receive_text()
  78. await websocket.send_text(
  79. f"Session cookie or query token value is: {cookie_or_token}"
  80. )
  81. if q is not None:
  82. await websocket.send_text(f"Query parameter q is: {q}")
  83. await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
  1. from typing import Union
  2. from fastapi import (
  3. Cookie,
  4. Depends,
  5. FastAPI,
  6. Query,
  7. WebSocket,
  8. WebSocketException,
  9. status,
  10. )
  11. from fastapi.responses import HTMLResponse
  12. from typing_extensions import Annotated
  13. app = FastAPI()
  14. html = """
  15. <!DOCTYPE html>
  16. <html>
  17. <head>
  18. <title>Chat</title>
  19. </head>
  20. <body>
  21. <h1>WebSocket Chat</h1>
  22. <form action="" onsubmit="sendMessage(event)">
  23. <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
  24. <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
  25. <button onclick="connect(event)">Connect</button>
  26. <hr>
  27. <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
  28. <button>Send</button>
  29. </form>
  30. <ul id='messages'>
  31. </ul>
  32. <script>
  33. var ws = null;
  34. function connect(event) {
  35. var itemId = document.getElementById("itemId")
  36. var token = document.getElementById("token")
  37. ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
  38. ws.onmessage = function(event) {
  39. var messages = document.getElementById('messages')
  40. var message = document.createElement('li')
  41. var content = document.createTextNode(event.data)
  42. message.appendChild(content)
  43. messages.appendChild(message)
  44. };
  45. event.preventDefault()
  46. }
  47. function sendMessage(event) {
  48. var input = document.getElementById("messageText")
  49. ws.send(input.value)
  50. input.value = ''
  51. event.preventDefault()
  52. }
  53. </script>
  54. </body>
  55. </html>
  56. """
  57. @app.get("/")
  58. async def get():
  59. return HTMLResponse(html)
  60. async def get_cookie_or_token(
  61. websocket: WebSocket,
  62. session: Annotated[Union[str, None], Cookie()] = None,
  63. token: Annotated[Union[str, None], Query()] = None,
  64. ):
  65. if session is None and token is None:
  66. raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
  67. return session or token
  68. @app.websocket("/items/{item_id}/ws")
  69. async def websocket_endpoint(
  70. *,
  71. websocket: WebSocket,
  72. item_id: str,
  73. q: Union[int, None] = None,
  74. cookie_or_token: Annotated[str, Depends(get_cookie_or_token)],
  75. ):
  76. await websocket.accept()
  77. while True:
  78. data = await websocket.receive_text()
  79. await websocket.send_text(
  80. f"Session cookie or query token value is: {cookie_or_token}"
  81. )
  82. if q is not None:
  83. await websocket.send_text(f"Query parameter q is: {q}")
  84. await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")

Tip

Prefer to use the Annotated version if possible.

  1. from fastapi import (
  2. Cookie,
  3. Depends,
  4. FastAPI,
  5. Query,
  6. WebSocket,
  7. WebSocketException,
  8. status,
  9. )
  10. from fastapi.responses import HTMLResponse
  11. app = FastAPI()
  12. html = """
  13. <!DOCTYPE html>
  14. <html>
  15. <head>
  16. <title>Chat</title>
  17. </head>
  18. <body>
  19. <h1>WebSocket Chat</h1>
  20. <form action="" onsubmit="sendMessage(event)">
  21. <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
  22. <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
  23. <button onclick="connect(event)">Connect</button>
  24. <hr>
  25. <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
  26. <button>Send</button>
  27. </form>
  28. <ul id='messages'>
  29. </ul>
  30. <script>
  31. var ws = null;
  32. function connect(event) {
  33. var itemId = document.getElementById("itemId")
  34. var token = document.getElementById("token")
  35. ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
  36. ws.onmessage = function(event) {
  37. var messages = document.getElementById('messages')
  38. var message = document.createElement('li')
  39. var content = document.createTextNode(event.data)
  40. message.appendChild(content)
  41. messages.appendChild(message)
  42. };
  43. event.preventDefault()
  44. }
  45. function sendMessage(event) {
  46. var input = document.getElementById("messageText")
  47. ws.send(input.value)
  48. input.value = ''
  49. event.preventDefault()
  50. }
  51. </script>
  52. </body>
  53. </html>
  54. """
  55. @app.get("/")
  56. async def get():
  57. return HTMLResponse(html)
  58. async def get_cookie_or_token(
  59. websocket: WebSocket,
  60. session: str | None = Cookie(default=None),
  61. token: str | None = Query(default=None),
  62. ):
  63. if session is None and token is None:
  64. raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
  65. return session or token
  66. @app.websocket("/items/{item_id}/ws")
  67. async def websocket_endpoint(
  68. websocket: WebSocket,
  69. item_id: str,
  70. q: int | None = None,
  71. cookie_or_token: str = Depends(get_cookie_or_token),
  72. ):
  73. await websocket.accept()
  74. while True:
  75. data = await websocket.receive_text()
  76. await websocket.send_text(
  77. f"Session cookie or query token value is: {cookie_or_token}"
  78. )
  79. if q is not None:
  80. await websocket.send_text(f"Query parameter q is: {q}")
  81. await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")

Tip

Prefer to use the Annotated version if possible.

  1. from typing import Union
  2. from fastapi import (
  3. Cookie,
  4. Depends,
  5. FastAPI,
  6. Query,
  7. WebSocket,
  8. WebSocketException,
  9. status,
  10. )
  11. from fastapi.responses import HTMLResponse
  12. app = FastAPI()
  13. html = """
  14. <!DOCTYPE html>
  15. <html>
  16. <head>
  17. <title>Chat</title>
  18. </head>
  19. <body>
  20. <h1>WebSocket Chat</h1>
  21. <form action="" onsubmit="sendMessage(event)">
  22. <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
  23. <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
  24. <button onclick="connect(event)">Connect</button>
  25. <hr>
  26. <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
  27. <button>Send</button>
  28. </form>
  29. <ul id='messages'>
  30. </ul>
  31. <script>
  32. var ws = null;
  33. function connect(event) {
  34. var itemId = document.getElementById("itemId")
  35. var token = document.getElementById("token")
  36. ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
  37. ws.onmessage = function(event) {
  38. var messages = document.getElementById('messages')
  39. var message = document.createElement('li')
  40. var content = document.createTextNode(event.data)
  41. message.appendChild(content)
  42. messages.appendChild(message)
  43. };
  44. event.preventDefault()
  45. }
  46. function sendMessage(event) {
  47. var input = document.getElementById("messageText")
  48. ws.send(input.value)
  49. input.value = ''
  50. event.preventDefault()
  51. }
  52. </script>
  53. </body>
  54. </html>
  55. """
  56. @app.get("/")
  57. async def get():
  58. return HTMLResponse(html)
  59. async def get_cookie_or_token(
  60. websocket: WebSocket,
  61. session: Union[str, None] = Cookie(default=None),
  62. token: Union[str, None] = Query(default=None),
  63. ):
  64. if session is None and token is None:
  65. raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
  66. return session or token
  67. @app.websocket("/items/{item_id}/ws")
  68. async def websocket_endpoint(
  69. websocket: WebSocket,
  70. item_id: str,
  71. q: Union[int, None] = None,
  72. cookie_or_token: str = Depends(get_cookie_or_token),
  73. ):
  74. await websocket.accept()
  75. while True:
  76. data = await websocket.receive_text()
  77. await websocket.send_text(
  78. f"Session cookie or query token value is: {cookie_or_token}"
  79. )
  80. if q is not None:
  81. await websocket.send_text(f"Query parameter q is: {q}")
  82. await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")

Info

As this is a WebSocket it doesn’t really make sense to raise an HTTPException, instead we raise a WebSocketException.

You can use a closing code from the valid codes defined in the specification.

Try the WebSockets with dependencies

If your file is named main.py, run your application with:

WebSockets - 图7

Open your browser at http://127.0.0.1:8000.

There you can set:

  • The “Item ID”, used in the path.
  • The “Token” used as a query parameter.

Tip

Notice that the query token will be handled by a dependency.

With that you can connect the WebSocket and then send and receive messages:

WebSockets - 图8

Handling disconnections and multiple clients

When a WebSocket connection is closed, the await websocket.receive_text() will raise a WebSocketDisconnect exception, which you can then catch and handle like in this example.

Python 3.9+Python 3.6+

  1. from fastapi import FastAPI, WebSocket, WebSocketDisconnect
  2. from fastapi.responses import HTMLResponse
  3. app = FastAPI()
  4. html = """
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <title>Chat</title>
  9. </head>
  10. <body>
  11. <h1>WebSocket Chat</h1>
  12. <h2>Your ID: <span id="ws-id"></span></h2>
  13. <form action="" onsubmit="sendMessage(event)">
  14. <input type="text" id="messageText" autocomplete="off"/>
  15. <button>Send</button>
  16. </form>
  17. <ul id='messages'>
  18. </ul>
  19. <script>
  20. var client_id = Date.now()
  21. document.querySelector("#ws-id").textContent = client_id;
  22. var ws = new WebSocket(`ws://localhost:8000/ws/${client_id}`);
  23. ws.onmessage = function(event) {
  24. var messages = document.getElementById('messages')
  25. var message = document.createElement('li')
  26. var content = document.createTextNode(event.data)
  27. message.appendChild(content)
  28. messages.appendChild(message)
  29. };
  30. function sendMessage(event) {
  31. var input = document.getElementById("messageText")
  32. ws.send(input.value)
  33. input.value = ''
  34. event.preventDefault()
  35. }
  36. </script>
  37. </body>
  38. </html>
  39. """
  40. class ConnectionManager:
  41. def __init__(self):
  42. self.active_connections: list[WebSocket] = []
  43. async def connect(self, websocket: WebSocket):
  44. await websocket.accept()
  45. self.active_connections.append(websocket)
  46. def disconnect(self, websocket: WebSocket):
  47. self.active_connections.remove(websocket)
  48. async def send_personal_message(self, message: str, websocket: WebSocket):
  49. await websocket.send_text(message)
  50. async def broadcast(self, message: str):
  51. for connection in self.active_connections:
  52. await connection.send_text(message)
  53. manager = ConnectionManager()
  54. @app.get("/")
  55. async def get():
  56. return HTMLResponse(html)
  57. @app.websocket("/ws/{client_id}")
  58. async def websocket_endpoint(websocket: WebSocket, client_id: int):
  59. await manager.connect(websocket)
  60. try:
  61. while True:
  62. data = await websocket.receive_text()
  63. await manager.send_personal_message(f"You wrote: {data}", websocket)
  64. await manager.broadcast(f"Client #{client_id} says: {data}")
  65. except WebSocketDisconnect:
  66. manager.disconnect(websocket)
  67. await manager.broadcast(f"Client #{client_id} left the chat")
  1. from typing import List
  2. from fastapi import FastAPI, WebSocket, WebSocketDisconnect
  3. from fastapi.responses import HTMLResponse
  4. app = FastAPI()
  5. html = """
  6. <!DOCTYPE html>
  7. <html>
  8. <head>
  9. <title>Chat</title>
  10. </head>
  11. <body>
  12. <h1>WebSocket Chat</h1>
  13. <h2>Your ID: <span id="ws-id"></span></h2>
  14. <form action="" onsubmit="sendMessage(event)">
  15. <input type="text" id="messageText" autocomplete="off"/>
  16. <button>Send</button>
  17. </form>
  18. <ul id='messages'>
  19. </ul>
  20. <script>
  21. var client_id = Date.now()
  22. document.querySelector("#ws-id").textContent = client_id;
  23. var ws = new WebSocket(`ws://localhost:8000/ws/${client_id}`);
  24. ws.onmessage = function(event) {
  25. var messages = document.getElementById('messages')
  26. var message = document.createElement('li')
  27. var content = document.createTextNode(event.data)
  28. message.appendChild(content)
  29. messages.appendChild(message)
  30. };
  31. function sendMessage(event) {
  32. var input = document.getElementById("messageText")
  33. ws.send(input.value)
  34. input.value = ''
  35. event.preventDefault()
  36. }
  37. </script>
  38. </body>
  39. </html>
  40. """
  41. class ConnectionManager:
  42. def __init__(self):
  43. self.active_connections: List[WebSocket] = []
  44. async def connect(self, websocket: WebSocket):
  45. await websocket.accept()
  46. self.active_connections.append(websocket)
  47. def disconnect(self, websocket: WebSocket):
  48. self.active_connections.remove(websocket)
  49. async def send_personal_message(self, message: str, websocket: WebSocket):
  50. await websocket.send_text(message)
  51. async def broadcast(self, message: str):
  52. for connection in self.active_connections:
  53. await connection.send_text(message)
  54. manager = ConnectionManager()
  55. @app.get("/")
  56. async def get():
  57. return HTMLResponse(html)
  58. @app.websocket("/ws/{client_id}")
  59. async def websocket_endpoint(websocket: WebSocket, client_id: int):
  60. await manager.connect(websocket)
  61. try:
  62. while True:
  63. data = await websocket.receive_text()
  64. await manager.send_personal_message(f"You wrote: {data}", websocket)
  65. await manager.broadcast(f"Client #{client_id} says: {data}")
  66. except WebSocketDisconnect:
  67. manager.disconnect(websocket)
  68. await manager.broadcast(f"Client #{client_id} left the chat")

To try it out:

  • Open the app with several browser tabs.
  • Write messages from them.
  • Then close one of the tabs.

That will raise the WebSocketDisconnect exception, and all the other clients will receive a message like:

  1. Client #1596980209979 left the chat

Tip

The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections.

But have in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process.

If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster.

More info

To learn more about the options, check Starlette’s documentation for: